1. <?php
  2. /**
  3. * Reads form field configurations from a configuration file.
  4. *
  5. * This function reads the form field configurations from a file
  6. * and returns an array of field definitions. It assumes a simple
  7. * format where each line represents a field and uses a key-value
  8. * pair separated by a colon.
  9. *
  10. * @param string $config_file Path to the configuration file.
  11. * @return array|false An array of field definitions, or false on error.
  12. */
  13. function readFormFieldConfig(string $config_file): array|false
  14. {
  15. $config = [];
  16. if (file_exists($config_file)) {
  17. // Open the configuration file for reading.
  18. $file = fopen($config_file, 'r');
  19. if ($file) {
  20. while (($line = fgets($file)) !== false) {
  21. // Trim whitespace from the line.
  22. $line = trim($line);
  23. // Skip empty lines and comments.
  24. if (empty($line) || strpos($line, '#') === 0) {
  25. continue;
  26. }
  27. // Split the line into key and value.
  28. list($key, $value) = explode(':', $line, 2);
  29. // Trim whitespace from the key and value.
  30. $key = trim($key);
  31. $value = trim($value);
  32. // Add the field definition to the array.
  33. $config[$key] = $value;
  34. }
  35. fclose($file);
  36. } else {
  37. // Handle file opening error.
  38. return false;
  39. }
  40. } else {
  41. // Handle file not found error.
  42. return false;
  43. }
  44. return $config;
  45. }
  46. /**
  47. * Example usage (demonstration). This is not part of the core function.
  48. */
  49. $config_file = 'form_config.txt'; // Replace with your config file.
  50. $form_fields = readFormFieldConfig($config_file);
  51. if ($form_fields !== false) {
  52. // Print the configuration.
  53. echo "<pre>";
  54. print_r($form_fields);
  55. echo "</pre>";
  56. // Access a specific field.
  57. if (isset($form_fields['name'])) {
  58. echo "Name field: " . $form_fields['name'] . "<br>";
  59. }
  60. } else {
  61. echo "Error reading form configuration.";
  62. }
  63. ?>

Add your comment