Wrap CSV values generated by PHP fputcsv() with “ ”

后端 未结 5 1210
忘了有多久
忘了有多久 2020-12-19 01:41

So, my code generates a CSV file using PHP\'s built-in fputcsv function.

For the delimiter, I use \',\' (a comma).
For the enclosure, I use \'

5条回答
  •  独厮守ぢ
    2020-12-19 02:27

    I worked around this by inserting some bogus string characters, with a space, #@ @#, and then removing them. Here's a sample implementation:

    //$exported is our array of data to export
    $filename = 'myfile.csv';
    $fp = fopen($filename, 'w');
    foreach ($exported as $line => $row) {
        if ($line > 0) {
            foreach ($row as $key => $value) {
                    $row[$key] = $value."#@ @#";
            }
        }
        fputcsv($fp, $row);
    }
    
    fclose($fp);
    $contents = file_get_contents($filename);
    $contents = str_replace("#@ @#", "", $contents);
    file_put_contents($filename, $contents);
    

    This encloses all fields in double quotes, including empty ones

提交回复
热议问题