I've spent some time looking at various posts on Stack Overflow regarding PHP CSV file manipulation and have devised a script that combines data from two CSV files to create two new files.
The aim of the task was to combine voucher numbers from one file to the customer data in another, along with the current date. I achieved this by extracting all the necessary data and writing it to a new file.
As some additional security/record keeping I've also combined the voucher data with the customer ID and current date to another file, for reference if needed.
I'm relatively new to PHP so your feedback would be greatly appreciated so that I might improve my code/logic:
// Open files for reading
$customers = fopen("customerTest1.csv", "r");
$vouchers = fopen("vouchersExtra.csv", "r+");
// Create new files to write data
$customerOutput = fopen("customerUpdated.csv", "w");
$voucherOutput = fopen("vouchersUpdated.csv", "w");
// Get columns from customer data and voucher data
$customerColumns = fgetcsv($customers, 1000);
$voucherColumns = fgetcsv($vouchers, 1000);
// Add extra columns for the output files
array_push($customerColumns, "voucherNumber", "dateApplied");
array_push($voucherColumns, "id", "dateUsed");
// Write the column headers to both customer and voucher output files
if (!$voucherOutput && !$customerOutput) {
die("$voucherOutput and $customerOutput BROKE");
} else {
fputcsv($customerOutput, $customerColumns);
fputcsv($voucherOutput, $voucherColumns);
}
// Open the input
if (!$customers) {
die("$customers BROKE");
} else {
while (!feof($customers)) {
// Extract current customer row of data
$currentCustomer = fgetcsv($customers, 1000);
// Only run the code if a current customer row exists
if ($currentCustomer != false) {
// Extract current voucher row of data
$currentVoucher = fgetcsv($vouchers, 1000);
// Get current customer's ID
$customerId = $currentCustomer[0];
// Merge customer and voucher data and push a date string to the end of the array
$newCustomerRow = array_merge($currentCustomer, $currentVoucher);
array_push($newCustomerRow, date("l jS \of F Y h:i:s A"));
// Merge voucher data, customer ID and push a date string to the end of the array
$newVoucherRow = [];
array_push($newVoucherRow, $currentVoucher[0], $customerId, date("l jS \of F Y h:i:s A"));
// Write new customer data to output file
fputcsv($customerOutput, $newCustomerRow);
// Write new voucher data to output file
fputcsv($voucherOutput, $newVoucherRow);
}
}
}