fputcsv()为每个条目添加引号?

时间:2016-10-03 09:58:19

标签: php csv export-to-csv fputcsv

使用此代码,我创建了CSV导出文件:

foreach ($data_for_export as $row) {
    $data = [];
    array_push($data, $row->product_id);
    array_push($data, $row->product_name);
    array_push($data, $row->product_code);
    array_push($data, $row->text);

    fputcsv($file, $data);
}

fclose($file);

示例输出是:

2131,"Toys set 35", TSSET35, "Lorem ipsum dolor sit amet"

我尝试过:

    preg_replace("/([a-z0-9]+)/i", '"$1"', $row->product_id)

    '"'.$row->product_id.'"'

使用“preg_replace”,我需要多次引用然后需要...

我需要所有导出项目的引号,我该怎么做?

1 个答案:

答案 0 :(得分:6)

通过 strval 功能将所有数据转换为字符串,然后尝试使用 fwrite 而不是 fputcsv

function push(&$data, $item) {
    $quote = chr(34); // quote " character from ASCII table
    $data[] = $quote . addslashes(strval($item)) . $quote;
}

foreach ($data_for_export as $row) {
    $data = [];

    push($data, $row->product_id);
    push($data, $row->product_name);
    push($data, $row->product_code);
    push($data, $row->text);

    // separate array items by ',' and add the End-Of-Line character
    fwrite($file, implode(',', $data) . PHP_EOL); 
}

fclose($file);