function generateCsv($data, $delimiter = ',', $enclosure = '"') {
$handle = fopen('php://temp', 'r+');
foreach ($data as $line) {
fputcsv($handle, $line, $delimiter, $enclosure);
}
rewind($handle);
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
return $contents;
}
用法
$data = array(
array(1, 2, 4),
array('test string', 'test, literal, comma', 'test literal "quotes"'),
);
echo generateCsv($data);
// outputs:
// 1,2,4
// "test string","test, literal, comma","test literal""quote"""
这个函数真棒!
这非常有用。我意识到这是一篇较旧的文章,但我想要指出,您似乎没有在追加到
$contents
之前声明它。太棒了,谢谢!
现在 PHP 中就是这样做的
https://php.ac.cn/manual/en/function.fputcsv.php
这个人添加了一个很好的功能——将数组键作为标题
输出标题
fputcsv($fh, array_keys(current($data)));
https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php
仅仅为了将数组转换为 CSV 而写入文件非常占用资源并且速度很慢。这是一种类似的方法,但只使用内存:https://coderwall.com/p/zvzwwa/array-to-comma-separated-string-in-php