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

时间:2016-04-25 07:45:02

标签: php api 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或同一目录中。

1 个答案:

答案 0 :(得分:0)

您可以将所有内容放入数组中。并使用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 here