<?php
/**
* Reads form field configurations from a configuration file.
*
* This function reads the form field configurations from a file
* and returns an array of field definitions. It assumes a simple
* format where each line represents a field and uses a key-value
* pair separated by a colon.
*
* @param string $config_file Path to the configuration file.
* @return array|false An array of field definitions, or false on error.
*/
function readFormFieldConfig(string $config_file): array|false
{
$config = [];
if (file_exists($config_file)) {
// Open the configuration file for reading.
$file = fopen($config_file, 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
// Trim whitespace from the line.
$line = trim($line);
// Skip empty lines and comments.
if (empty($line) || strpos($line, '#') === 0) {
continue;
}
// Split the line into key and value.
list($key, $value) = explode(':', $line, 2);
// Trim whitespace from the key and value.
$key = trim($key);
$value = trim($value);
// Add the field definition to the array.
$config[$key] = $value;
}
fclose($file);
} else {
// Handle file opening error.
return false;
}
} else {
// Handle file not found error.
return false;
}
return $config;
}
/**
* Example usage (demonstration). This is not part of the core function.
*/
$config_file = 'form_config.txt'; // Replace with your config file.
$form_fields = readFormFieldConfig($config_file);
if ($form_fields !== false) {
// Print the configuration.
echo "<pre>";
print_r($form_fields);
echo "</pre>";
// Access a specific field.
if (isset($form_fields['name'])) {
echo "Name field: " . $form_fields['name'] . "<br>";
}
} else {
echo "Error reading form configuration.";
}
?>
Add your comment