1. <?php
  2. /**
  3. * Flattens a text file structure.
  4. *
  5. * This function reads a text file, interprets its structure
  6. * (assuming a specific format), and outputs a flattened string.
  7. * Supports older PHP versions.
  8. *
  9. * @param string $filePath The path to the text file.
  10. * @param string $delimiter The delimiter separating key-value pairs.
  11. * @param string $newline The newline character.
  12. * @return string The flattened string.
  13. */
  14. function flattenTextFile(string $filePath, string $delimiter = '=', string $newline = "\n"): string
  15. {
  16. $flattenedString = '';
  17. if (!file_exists($filePath)) {
  18. return "Error: File not found at $filePath";
  19. }
  20. $file = fopen($filePath, 'r');
  21. if ($file === false) {
  22. return "Error: Could not open file at $filePath";
  23. }
  24. while (($line = fgets($file)) !== false) {
  25. // Trim whitespace
  26. $line = trim($line);
  27. // Skip empty lines and comments
  28. if (empty($line) || strpos($line, '#') === 0) {
  29. continue;
  30. }
  31. // Split the line into key and value
  32. $parts = explode($delimiter, $line, 2);
  33. if (count($parts) === 2) {
  34. $key = trim($parts[0]);
  35. $value = trim($parts[1]);
  36. // Escape special characters in the key for safe output
  37. $key = htmlspecialchars($key);
  38. // Append the flattened key-value pair to the string
  39. $flattenedString .= "$key: $value$newline";
  40. }
  41. }
  42. fclose($file);
  43. return $flattenedString;
  44. }
  45. //Example usage (for testing)
  46. /*
  47. $filePath = 'data.txt'; // Replace with your file path
  48. // Create a sample file for testing
  49. $testData = "name=John Doe\n# This is a comment\nage=30\ncity=New York\nemail=john.doe@example.com";
  50. file_put_contents($filePath, $testData);
  51. $flattenedData = flattenTextFile($filePath);
  52. echo $flattenedData;
  53. //Clean up the test file
  54. unlink($filePath);
  55. */
  56. ?>

Add your comment