PHP -从POST $data = curl_exec($ch)创建CSV文件;只包含一个大字符串

x7rlezfr  于 2023-07-31  发布在  PHP
关注(0)|答案(3)|浏览(89)

$data = curl_exec($ch);使用POST方法
当我回显'<pre>',var_dump($data),'</pre>';

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

字符串
我试着把它们拆分成数组$lines = str_getcsv($data, PHP_EOL);
但是我只有一个数组,所有的东西都在里面
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""


我想创建一个csv文件。我就这么做了

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


我得到了文件,但在Excel中打开时,列不正确。
如何将它们逐行拆分?
谢谢

i7uq4tfw

i7uq4tfw1#

请注意,您的数据已经是csv。简而言之,除了将其保存到一个带有file_put_contents的文件中之外,您无需做任何事情。
关于您的方法:您只会在数组中获得一个项目,因为:

  • str_getcsv被设计为只读取一行csv,而不是多行的整个csv字符串。
  • str_getcsv的第二个参数不是行分隔符(参见手册),而是不是换行符的项目分隔符。

但是如果你想改变csv的外观(分隔符、保护或转义字符、换行符),你必须逐行读取并写入它。一种简单的方法是使用fopen()data:// wrapper,例如,从一个简单的字符串中获取资源。这样你就不必按行分割数据了,因为fgetcsv已经为你做了:

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

字符串

uoifb46i

uoifb46i2#

似乎有些微软的Excel版本倾向于使用分号';'而不是逗号','如(https://answers.microsoft.com/en-us/msoffice/forum/all/excel-keeps-on-using-semicolon-instead-of-comma/543510d9-65a8-4a0d-8464-a08fc0ac1c4f)所示。它还可能取决于区域设置和用户设置。
在这种情况下,从','变为';’可以根据用户请求而被需要。
例如,对于下面的数据...

// obtained data
$data = '"A","B","C","D","E","F","G","H"
,"2",,"4","5",,,"8"
"ONE",,,"QW AH",,"US",,"EU"';

// break it into lines
$lines = explode(PHP_EOL, $data);

// haven for the formatted rows
$csv_rows = [];

foreach ($lines as $line) {
    // Breaks each line into cells by the comma,
    // ignoring eventual commas inside values
    $cells = preg_split('/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/', $line);

    // joins cells with semicolon
    $csv_rows[] = implode(';', $cells);
}

// result
$csv_text = implode(PHP_EOL, $csv_rows);

字符串
结果文本:

"A";"B";"C";"D";"E";"F";"G";"H"
;"2";;"4";"5";;;"8" "ONE";;;"QW
AH";;"US";;"EU"


在PHP Sandbox中测试→ https://onlinephp.io/c/23cc3
我们欢迎改进。

slwdgvem

slwdgvem3#

只是为了提醒我自己或任何感兴趣的人。这就是我最终得到我想要的文件所做的。
移除

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

字符串
并更改为file_put_contents('../myfile.csv','w');
非常感谢你们为我解释这一点,并展示了更多的奖金知识:)

相关问题