将逗号分隔的 API 响应转换为 CSV


Converting comma-separated API response to CSV

我正在运行一个API,这个API的响应以逗号分隔的值返回响应。

我正在$result返回回复.

响应:

lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type 106864,new,"Gift Vouchers worth ₹2000 @ for just ₹999","Get it for just ₹999",,"Gift Items","ABC Company",http://example1.com,http://example2.com,"2016-04-07 00:00:00","2016-05-01 00:00:00",sale

以下是响应中的标头:

lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type

我尝试过的代码:

  function str_putcsv($result) {
        # Generate CSV data from array
        $fh = fopen('php://temp', 'rw'); # don't create a file, attempt
                                         # to use memory instead
        # write out the headers
        fputcsv($fh, array_keys(current($result)));
        # write out the data
        foreach ( $result as $row ) {
                fputcsv($fh, $row);
        }
        rewind($fh);
        $csv = stream_get_contents($fh);
        fclose($fh);
        return $csv;
}

使用上面的代码,我无法找到此代码生成CSV的位置。

另一个代码:

    $fp = fopen('data.csv', 'w');
foreach($data as $line){
    $val = explode(",",$line);
    fputcsv($fp, $val);
}
fclose($fp);

上面的代码正在FTP上生成文件,但其中没有数据。它正在生成空白的 CSV。

我想将此响应转换为CSV文件并将其放在FTP或同一目录中。

您可以将所有内容放在一个数组中。并使用int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "'" ]]] )

php.net 的例子:

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
$fp = fopen('path/to/file.csv', 'w');
foreach ($list as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

在此处阅读有关 FGETCSV 的更多信息