0

我正在使用fputcsv它,它只是将输入文本类型值放入引号中。有没有办法覆盖它并强制所有引号或将它们全部删除?我试过fputcsv($fp, $data, ',', '"');了,但没用

$data = array_values($_POST);
if( $fp = fopen('data.csv', 'a+') ){
    fputcsv($fp, $data);
}
fclose($fp);

csv 数据示例:"user","city",yes,no,10001

4

1 回答 1

1

您可以通过附加一个空格来强制引用每个条目,然后在将其写入 .csv 之前使用流过滤器删除该空格

/* Function to append a space to each element in the array */
function addSpace(&$var, $key){ $var .= ' '; }

/* Filter class to remove the space previously appended */
class space_filter extends php_user_filter {
  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $bucket->data = str_replace(' "', '"', $bucket->data);
      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }
}

/* Register filter */
stream_filter_register("filterspace", "space_filter");

$arr = array("user","city","yes","no","10001"); // your array

/* use addSpace on each element in the array */
array_walk($arr, "addSpace");

if( $fp = fopen('data.csv', 'a+') ){
    stream_filter_append($fp, "filterspace"); // Remove space 
    fputcsv($fp, $arr);
}
fclose($fp);    

结果:“用户”、“城市”、“是”、“否”、“10001”

我只是出于好奇而写了这个,你可能不应该将它用于任何重要的事情。

于 2012-08-18T06:34:53.993 回答