I need to have a script that I can upload a CSV to and have it output the contents in a new order with some fields removed and some added. I have tried getting the csv into an array but emails seem to break it. An input might look like this:
col1, col2, col3, col4
name, addr, phon, emal
...
The output would need to be changed to:
col4, col1, col3, col5
emal, name, addr, stat
...
Notice col3 is gone and col5 is added. col5 is the same value for every row.
I was doing this with a foreach loop. Which worked but its kind of slow. I dont know if there is a better or faster way.
Edit:
The answer seems to work but it raises two other features that will help:
One, I have a field that includes a date and time like 1/31/15 23:59
. is there an easy way to strip the last 6 characters?
Two, can we skip a line if say col3
has data? I have a refunded date column that I would like to skip over if theres a date in it. Its blank otherwise. I know I can use isset but I dont know how to make the loop skip and continue if col3
isset. Also I dont know if isset might still be TRUE if theres no data since the column still exists
<?php
$sInFile = 'infile.csv';
$sOutFile = 'outfile.csv';
$iRow = 0;
if( ( $rHandle = fopen( $sInFile, "r")) !== FALSE )
{
while( ( $aData = fgetcsv( $rHandle, 1000, ",") ) !== FALSE )
{
// Skip headers.
if( $iRow != 0 )
{
$iCountColumns = count( $aData );
for( $i = 0; $i < $iCountColumns; ++$i )
{
// Source
// name, addr, phon, emal
$sTmp = '';
$sTmp .= $aData[ 3 ];
$sTmp .= ', ';
$sTmp .= $aData[ 0 ];
$sTmp .= ', ';
$sTmp .= $aData[ 1 ];
$sTmp .= ', ';
$sTmp .= 'CONSTANT!';
$sTmp .= "
";
// Output
// emal, name, addr, stat
}
file_put_contents( $sOutFile, $sTmp, FILE_APPEND | LOCK_EX );
}
++$iRow;
}
}
?>