且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在CSV文件中插入新行?

更新时间:2023-11-18 22:43:22

正如其他人所说,使用PHP_EOL生成新行.

As others have said, use PHP_EOL to generate a new line.

但是,我会自己使用 fputcsv 来确保内容正确封装:

However, I would use fputcsv myself to ensure the contents were correctly enclosed:

function generateCsv(array $data, $filename,  $delimiter = ',', $enclosure = '"') {
    $handle = fopen($filename, 'r+');
    foreach ($data as $line) {
        fputcsv($handle, $line, $delimiter, $enclosure);
    }
    rewind($handle);
    $contents = '';
    while (!feof($handle)) {
        $contents .= fread($handle, 8192);
    }
    fclose($handle);
    return $contents;
}

// usage
echo generateCsv($data, '/path/to/file.csv');

// or just save the csv to file:
generateCsv($data, '/path/to/file.csv');

此功能以及将csv保存到 $ filename 的功能,如果您喜欢 echo ,也会将生成的csv作为字符串返回.

This function, as well as saving the csv to $filename also returns the generated csv as a string if you fancy echoing it.