Is there a function or library that converts arrays into csv in php?

Asked 2 years ago, Updated 2 years ago, 79 views

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"

php csv

2022-09-29 22:38

2 Answers

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


2022-09-29 22:38

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;
}


2022-09-29 22:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.