有没有函数可以获取字符串数组并返回 CSV 行?

gam*_*ver 2 php

我有一个字符串数组,想要一种从它们创建 CSV 行的方法。就像是:

$CSV_line = implode(',',$pieces);
Run Code Online (Sandbox Code Playgroud)

不起作用,因为这些片段可能包含逗号和双引号。
是否有 PHP 内置函数可以获取这些片段并返回格式良好的 CSV 行?

谢谢,
罗杰

Pas*_*TIN 5

如果你想将该行写入文件,你可以使用fputcsv


使用 PHP 的流功能,应该可以写入变量——事实上,评论中有人str_getcsv发布了他的实现str_putcsv

<?php
function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
  // Open a memory "file" for read/write...
  $fp = fopen('php://temp', 'r+');
  // ... write the $input array to the "file" using fputcsv()...
  fputcsv($fp, $input, $delimiter, $enclosure);
  // ... rewind the "file" so we can read what we just wrote...
  rewind($fp);
  // ... read the entire line into a variable...
  $data = fread($fp, 1048576); // [changed]
  // ... close the "file"...
  fclose($fp);
  // ... and return the $data to the caller, with the trailing newline from fgets() removed.
  return rtrim( $data, "\n" );
}
?>
Run Code Online (Sandbox Code Playgroud)

注意:这段代码不是我的——它是Ulf在 php.net 上发布的代码的复制粘贴。