<?php
/**
* Flattens nested log structures from files.
*
* Usage: php flatten_logs.php <input_file> [output_file]
*
* @param string $inputFile Path to the input log file.
* @param string $outputFile Optional path to the output flattened file. If not provided, output to STDOUT.
* @return void
*/
function flattenLogs(string $inputFile, string $outputFile = null): void
{
if (!file_exists($inputFile)) {
die("Error: Input file '$inputFile' not found.");
}
$lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // Read file lines
if ($lines === false) {
die("Error: Could not read input file '$inputFile'.");
}
$flattenedData = [];
foreach ($lines as $line) {
$data = json_decode($line, true); // Decode JSON line
if ($data === null) {
continue; // Skip invalid JSON lines
}
// Recursive flattening function
function flattenArray($arr, string $prefix = ""): array {
$newArr = [];
foreach ($arr as $key => $value) {
$newKey = $prefix ? $prefix . "_" . $key : $key;
if (is_array($value)) {
$newArr = array_merge($newArr, flattenArray($value, $newKey)); // Recursive call
} else {
$newArr[$newKey] = $value;
}
}
return $newArr;
}
$flattenedData[] = flattenArray($data);
}
// Output the flattened data
if ($outputFile) {
file_put_contents($outputFile, json_encode($flattenedData, JSON_PRETTY_PRINT)); // Write to file
} else {
echo json_encode($flattenedData, JSON_PRETTY_PRINT); // Output to STDOUT
}
}
if (count($argv) < 2 || count($argv) > 3) {
die("Usage: php flatten_logs.php <input_file> [output_file]");
}
$inputFile = $argv[1];
$outputFile = $argv[2] ?? null;
flattenLogs($inputFile, $outputFile);
Add your comment