PHP: csv generator creates extra field
Posted
by WhyKiki
on Stack Overflow
See other posts from Stack Overflow
or by WhyKiki
Published on 2010-04-18T14:21:24Z
Indexed on
2010/04/18
14:23 UTC
Read the original article
Hit count: 192
I'm coding a script that takes one csv file to transform it into another one. Basically, two foreach loops are used: one to iterate records and another to iterate fields. Certain fields (cno 25, 26, 44) for each record needs to be modified. The problem is that each modificatino creates an extra empty field, i.e. the code
$colStr .= '"' . $col . '";';
works but not any of the code in the if statements.
The code is:
$rno = 0;
foreach ($csvArray as $line)
{
$cno = 0;
$colStr = "";
foreach ($line as $col)
{
if($rno>0 && $cno==25)
{
$stuff = array($csvArray[$rno][41], $csvArray[$rno][47], $csvArray[$rno][48], $csvArray[$rno][49]);
foreach($stuff as &$value)
{
$value = preg_replace('/[^0-9]/', '', $value);
}
sort($stuff, SORT_NUMERIC);
// Causes bug!
$colStr .= '"' . $stuff[0] . '";';
}
if($rno>0 && $cno==26)
{
$urls = "";
for($i = 55; $i<=62; $i++)
{
$urls .= "Images: " . $csvArray[$rno][$i] . " | ";
}
$urls .= "Some text: " . $csvArray[$rno][43] . " | ";
// Causes bug!
$colStr .= '"' . $urls . '";';
}
if($rno>0 && $cno==44)
{
$colStr .= '"' . $_POST['location'][$rno] . '";';
}
if($rno>0 && $cno==54)
{
$objType = $col;
$objType = preg_replace('/foobar/i', '123', $objType);
// Causes bug!
$colStr .= '"' . $objType . '";';
}
else
{
// This is ok, though
$colStr .= '"' . $col . '";';
}
$cno++;
}
$colStr = preg_replace('/;$/', '', $colStr);
$colStr .= "\n";
fwrite($outputFile, $colStr);
$rno++;
}
fclose($outputFile);
© Stack Overflow or respective owner