<?php
/**
* Aggregates form submissions for data migration.
*
* This script reads data from a specified file (e.g., CSV, JSON)
* and aggregates values based on a key. It's designed for minimal
* configuration.
*
* Usage:
* php aggregate_data.php <input_file> <output_file> <aggregation_key>
*
* <input_file>: Path to the file containing form submissions.
* <output_file>: Path to the file where aggregated data will be saved (CSV).
* <aggregation_key>: The key to group data by.
*/
// --- Configuration ---
$inputFile = $argv[1]; // Input file path
$outputFile = $argv[2]; // Output file path
$aggregationKey = $argv[3]; // Key to aggregate by
// --- Data Loading & Aggregation ---
try {
// Attempt to load data from CSV. Adapt for other formats (JSON, XML)
$data = [];
if (substr($inputFile, -3) === 'csv') {
$handle = fopen($inputFile, 'r');
if ($handle) {
$header = fgetcsv($handle);
while (($row = fgetcsv($handle)) !== FALSE) {
$data[$row[$aggregationKey]] = $row[0]; // Aggregate value (assuming first column)
}
fclose($handle);
} else {
throw new Exception("Failed to open input file.");
}
} else {
throw new Exception("Unsupported input file format. Only CSV supported.");
}
// --- Output to CSV ---
$output = fopen($outputFile, 'w');
if ($output) {
fputcsv($output, ['Aggregation Key', 'Aggregated Value']);
foreach ($data as $key => $value) {
fputcsv($output, [$key, $value]);
}
fclose($output);
} else {
throw new Exception("Failed to open output file.");
}
echo "Data aggregated and saved to: " . $outputFile . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
exit(1);
}
?>
Add your comment