<?php
/**
* Flattens a text file structure.
*
* This function reads a text file, interprets its structure
* (assuming a specific format), and outputs a flattened string.
* Supports older PHP versions.
*
* @param string $filePath The path to the text file.
* @param string $delimiter The delimiter separating key-value pairs.
* @param string $newline The newline character.
* @return string The flattened string.
*/
function flattenTextFile(string $filePath, string $delimiter = '=', string $newline = "\n"): string
{
$flattenedString = '';
if (!file_exists($filePath)) {
return "Error: File not found at $filePath";
}
$file = fopen($filePath, 'r');
if ($file === false) {
return "Error: Could not open file at $filePath";
}
while (($line = fgets($file)) !== false) {
// Trim whitespace
$line = trim($line);
// Skip empty lines and comments
if (empty($line) || strpos($line, '#') === 0) {
continue;
}
// Split the line into key and value
$parts = explode($delimiter, $line, 2);
if (count($parts) === 2) {
$key = trim($parts[0]);
$value = trim($parts[1]);
// Escape special characters in the key for safe output
$key = htmlspecialchars($key);
// Append the flattened key-value pair to the string
$flattenedString .= "$key: $value$newline";
}
}
fclose($file);
return $flattenedString;
}
//Example usage (for testing)
/*
$filePath = 'data.txt'; // Replace with your file path
// Create a sample file for testing
$testData = "name=John Doe\n# This is a comment\nage=30\ncity=New York\nemail=john.doe@example.com";
file_put_contents($filePath, $testData);
$flattenedData = flattenTextFile($filePath);
echo $flattenedData;
//Clean up the test file
unlink($filePath);
*/
?>
Add your comment