I want to get every single .CSV file from csvinput
directory, format and modify it and save in csvoutput
directory, then delete processed files from input folder. The problem is that when there is only one file in input folder, output .CSV file is as it's expected, but when there is two or more files, only first output .CSV file is formatted as expected and others have some unwanted data left and other lines filled.
I'm running foreach
loop to irritate through .csv files and process them. Here is my complete code for that.
<?php
$inputfiles = glob("csvinput/*.csv");
$skip = true;
foreach($inputfiles as $inputfile) {
if (($input = fopen($inputfile, "r")) !== false) {
if (($output = fopen('csvoutput/OUTPUT_'.basename($inputfile), 'w')) !== false) {
$headers = array("Product Code", "Ship Direct Flag", "Delivery Flash", "WEB Price", "WP Promo Price", "GS Promo Price", "Stock Level", "Stock Promise Date", "DROPPEDLINE");
fputcsv($output, $headers);
while(($data = fgetcsv($input))) {
if ($skip) { $skip = false; continue; }
if (array_filter($data)) {
$available_for_sales = $data[0];
$code = $data[1];
$buying_price = $data[7];
$stock_level = $data[13];
$data[0] = 'DS-'.$code;
$data[1] = 'STOCKED';
$data[2] = '';
$data[3] = $buying_price;
$data[4] = $buying_price;
$data[5] = $buying_price;
$data[6] = $stock_level;
$data[7] = date("Y-m-d",strtotime("tomorrow"));
$data[8] = strtr($available_for_sales,array("1" => "N","0" => "Y"));
}
fputcsv($output, array_slice($data, 0, 9));
}
fclose( $input );
fclose( $output );
unlink($inputfile);
echo 'Successfully processed <b>' .basename($inputfile). '</b><br>';
} else {
echo "Could not create file: OUTPUT_".basename($inputfile);
}
} else {
echo "Could not open file: " .basename($inputfile);
}
}
?>
My input files looks like this: input
Expected output files should look like this: output
But if there is more than one input file, then all other output files except first look like this: uglyoutput