开发者

Write to a CSV file on two columns

开发者 https://www.devze.com 2022-12-15 11:32 出处:网络
I am try开发者_JS百科ing 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.

I am try开发者_JS百科ing 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?


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().


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消