1. <?php
  2. /**
  3. * Aggregates form submissions for data migration.
  4. *
  5. * This script reads data from a specified file (e.g., CSV, JSON)
  6. * and aggregates values based on a key. It's designed for minimal
  7. * configuration.
  8. *
  9. * Usage:
  10. * php aggregate_data.php <input_file> <output_file> <aggregation_key>
  11. *
  12. * <input_file>: Path to the file containing form submissions.
  13. * <output_file>: Path to the file where aggregated data will be saved (CSV).
  14. * <aggregation_key>: The key to group data by.
  15. */
  16. // --- Configuration ---
  17. $inputFile = $argv[1]; // Input file path
  18. $outputFile = $argv[2]; // Output file path
  19. $aggregationKey = $argv[3]; // Key to aggregate by
  20. // --- Data Loading & Aggregation ---
  21. try {
  22. // Attempt to load data from CSV. Adapt for other formats (JSON, XML)
  23. $data = [];
  24. if (substr($inputFile, -3) === 'csv') {
  25. $handle = fopen($inputFile, 'r');
  26. if ($handle) {
  27. $header = fgetcsv($handle);
  28. while (($row = fgetcsv($handle)) !== FALSE) {
  29. $data[$row[$aggregationKey]] = $row[0]; // Aggregate value (assuming first column)
  30. }
  31. fclose($handle);
  32. } else {
  33. throw new Exception("Failed to open input file.");
  34. }
  35. } else {
  36. throw new Exception("Unsupported input file format. Only CSV supported.");
  37. }
  38. // --- Output to CSV ---
  39. $output = fopen($outputFile, 'w');
  40. if ($output) {
  41. fputcsv($output, ['Aggregation Key', 'Aggregated Value']);
  42. foreach ($data as $key => $value) {
  43. fputcsv($output, [$key, $value]);
  44. }
  45. fclose($output);
  46. } else {
  47. throw new Exception("Failed to open output file.");
  48. }
  49. echo "Data aggregated and saved to: " . $outputFile . "\n";
  50. } catch (Exception $e) {
  51. echo "Error: " . $e->getMessage() . "\n";
  52. exit(1);
  53. }
  54. ?>

Add your comment