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.
2
Answers
It seems some Microsof Excel versions tend to use semicolon ‘;’ instead of comma ‘,’ as seen at (https://answers.microsoft.com/en-us/msoffice/forum/all/excel-keeps-on-using-semicolon-instead-of-comma/543510d9-65a8-4a0d-8464-a08fc0ac1c4f). It also may depend on locale and user settings.
In such case, changes from ‘,’ to ‘;’ may be needed according to user request.
E.g., for the data below…
Result text:
Tested within PHP Sandbox
→ https://onlinephp.io/c/23cc3
Improvements are welcome.
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:
str_getcsv
is designed to read only one line of csv, not a whole csv string with multiple lines.str_getcsv
is not the line separator (see the manual) but the item separator that isn’t a newline.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 thedata://
wrapper, for example, to obtain a resource from a simple string. This way you don’t have to split your data by lines sincefgetcsv
does it for you: