As per the title, how can I convert the array to CSV in a good way?
It is ideal to close it with a double-quote if necessary just by passing through a function.
Also, it would be better to return it as a string instead of the type to print files like fputcsv.
[
[1, "hoge", "fuga", "piyo\npiyo",
[2, "hoge", "fuga", "piyo\npiyo",
[3, "hoge", "fuga", "piyo\npiyo"]
];
↓
1, hoge, fuga, "piyo\npiyo"
2, hoge, fuga, "piyo\npiyo"
3, hoge, fuga, "piyo\npiyo"
It has not been verified, but it seems that it can be done by outputting fputcsv
to memory.
The rest can be accessed just like a file.
$fp=fopen('php://memory','r+');
foreach($csv_data as$line){
fputcsv($fp,$line);
}
refresh($fp);
while(!feof($fp){
print(fgets($fp,1024);
}
fclose($fp);
Note: Store fputcsv results in variables instead of writing them to a file
PHP has str_getcsv, but not str_putcsv.It's rare for a PHP with everything.So I think you have to write it in memory and then read it out.However, there is a convenient class called SplFileObject, so why don't you try it?
$csv=newSplFileObject('php://memory', 'wr+');
$csv->fputcsv([1, "hoge", "fuga", "piyo\npiyo"));
$csv->fputcsv([2, "hoge", "fuga", "piyo\npiyo"));
$csv->fputcsv([3, "hoge", "fuga", "piyo\npiyo"));
foreach($csvas$text){
echo$text;
}
© 2024 OneMinuteCode. All rights reserved.