tags:

views:

175

answers:

2

Hello all,

I am trying to create a CSV file. I have done this. I have put the below in a loop with the first and last lines outside of the loop.

$FileHandle = fopen('tech.csv', 'a+') or die("can't open file");
$stringa = $item." , ".$item2."\r\n";
fwrite($FileHandle, $stringa);
fclose($FileHandle);

However, it comes out like this in the CSV file:

a
b

c
d

Rather than the way I want it:

a b
c d

Basically, two columns rather than one.

What am I doing wrong?

+3  A: 

I really hope you don't open and close the file in every iteration as that puts a real strain on the filesystem. Instead, you could do something like this:

$csv = array();
foreach($myData as $row) {
    $csv[] = trim($row['item1']).','.trim($row['item2']);
}
file_put_contents('tech.csv', implode("\r\n", $csv), FILE_APPEND);

Or, you could use the fputcsv function:

$fp = fopen('tech.csv', 'a+');
foreach($myData as $row) {
    fputcsv($fp, array(trim($row['item1']), trim($row['item2']));
}    
fclose($fp);
Tatu Ulmanen
The code sample in the OP appends to an existing file (`a+`), whereas this code overwrites whatever is there.
nickf
@nickf, I suspect that's because he's doing the opening and closing in every iteration if I understood him correctly, but I changed my examples so that they're appending to avoid confusion.
Tatu Ulmanen
I am not opening or closing in the loop! I said I put the first and second line outside the loop in my question. :)
Abs
+3  A: 

Do you read those values from a file/stream using fgets()? Then the trailing linebreak is part of the string. Use trim() to remove the linebreak.

You might also be interested in the function fputcsv().

VolkerK
Fantastic, trim did the job. The string is from a web page and I can imagine it having a trailing line break. Thanks VolKerK. :)
Abs