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

Php 将逗号分隔的API响应转换为CSV,php,api,csv,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 Compa

我正在运行一个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(资源$handle,数组$fields[,string$delimiter=“,”[,string$enclosure='”[,string$escape\u 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的更多信息

您应该发布到目前为止您的treid。人们会愿意帮助您改进/修复代码,但这不是编码服务。可能重复