1. <?php
  2. /**
  3. * Flattens nested log structures from files.
  4. *
  5. * Usage: php flatten_logs.php <input_file> [output_file]
  6. *
  7. * @param string $inputFile Path to the input log file.
  8. * @param string $outputFile Optional path to the output flattened file. If not provided, output to STDOUT.
  9. * @return void
  10. */
  11. function flattenLogs(string $inputFile, string $outputFile = null): void
  12. {
  13. if (!file_exists($inputFile)) {
  14. die("Error: Input file '$inputFile' not found.");
  15. }
  16. $lines = file($inputFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // Read file lines
  17. if ($lines === false) {
  18. die("Error: Could not read input file '$inputFile'.");
  19. }
  20. $flattenedData = [];
  21. foreach ($lines as $line) {
  22. $data = json_decode($line, true); // Decode JSON line
  23. if ($data === null) {
  24. continue; // Skip invalid JSON lines
  25. }
  26. // Recursive flattening function
  27. function flattenArray($arr, string $prefix = ""): array {
  28. $newArr = [];
  29. foreach ($arr as $key => $value) {
  30. $newKey = $prefix ? $prefix . "_" . $key : $key;
  31. if (is_array($value)) {
  32. $newArr = array_merge($newArr, flattenArray($value, $newKey)); // Recursive call
  33. } else {
  34. $newArr[$newKey] = $value;
  35. }
  36. }
  37. return $newArr;
  38. }
  39. $flattenedData[] = flattenArray($data);
  40. }
  41. // Output the flattened data
  42. if ($outputFile) {
  43. file_put_contents($outputFile, json_encode($flattenedData, JSON_PRETTY_PRINT)); // Write to file
  44. } else {
  45. echo json_encode($flattenedData, JSON_PRETTY_PRINT); // Output to STDOUT
  46. }
  47. }
  48. if (count($argv) < 2 || count($argv) > 3) {
  49. die("Usage: php flatten_logs.php <input_file> [output_file]");
  50. }
  51. $inputFile = $argv[1];
  52. $outputFile = $argv[2] ?? null;
  53. flattenLogs($inputFile, $outputFile);

Add your comment