phpcsvcurlpostfputcsv

PHP - create CSV file from POST $data = curl_exec($ch); that Contains only 1 big String


I did $data = curl_exec($ch); with POST method.
When I did echo '<pre>',var_dump($data),'</pre>';

string(15124) ""A","B","C","D","E","F","G","H"
,"2",,"4","5",,,"8"
"ONE",,,"QW AH",,"US",,"EU""

I tried to split them and make into array $lines = str_getcsv($data, PHP_EOL);
But I got only 1 array with everything in it
echo '<pre>',var_dump($lines),'</pre>';

array(1) {
  [0]=>
  string(15121) ""A","B","C","D","E","F","G","H"
,"2",,"4","5",,,"8"
"ONE",,,"QW AH",,"US",,"EU""

I want to create a csv file from that. So I did

$fp = fopen('../myfile.csv','w');
    fputcsv($fp, $data);
fclose($fp);

I got the file, but when opened in excel the columns are not right.
How to actually split them row by row?
Thanks.


Solution

  • Note that your data are already a csv. In short you have nothing to do except to save it to a file with file_put_contents.

    About your approach: You obtain only one item in your array because:

    But if you want to change how the csv looks like (the delimiter, the protection or escape character, the newline sequence), you have to read it and to write it line by line. A simple way to do that is to use fopen() with the data:// wrapper, for example, to obtain a resource from a simple string. This way you don't have to split your data by lines since fgetcsv does it for you:

    $data = '"A","B","C","D","E","F","G","H"
    ,"2",,"4","5",,,"8"
    "ONE",,,"QW AH",,"US",,"EU"';
        
    $fhi = fopen('data://text/plain;base64,' . base64_encode($data), 'r');
    
    if (false !== $fho = fopen('output.csv', 'w')) {
        while (false !== $row = fgetcsv($fhi)) {
            fputcsv($fho, $row, ';', '"', '\\', "\n"); // choose the parameters
        }
        
        close($fho);
    }
    
    close($fhi);