【问题标题】:php fputcsv and enclosing fieldsphp fputcsv 和封闭字段
【发布时间】:2011-01-31 15:47:33
【问题描述】:

我正要问与这里提出的问题相同的问题....Forcing fputcsv to Use Enclosure For *all* Fields

问题是

当我使用 fputcsv 写出一行时 到打开的文件句柄,PHP 将添加 任何列的封闭字符 它认为需要它,但会 保留其他列而不使用 外壳。

例如,您最终可能会得到一个 像这样的线

11,"Bob ",Jenkins,"200 main st. USA "等

没有附加一个虚假的空格 每个领域的尽头,有没有 强制 fputcsv 始终包含的方法 带外壳的列(默认值 到一个 ") 字符?

答案是:

不,fputcsv() 仅包含该字段 在以下条件下

/* enclose a field that contains a delimiter, an enclosure character, or a newline */
if (FPUTCSV_FLD_CHK(delimiter) ||
  FPUTCSV_FLD_CHK(enclosure) ||
  FPUTCSV_FLD_CHK(escape_char) ||
  FPUTCSV_FLD_CHK('\n') ||
  FPUTCSV_FLD_CHK('\r') ||
  FPUTCSV_FLD_CHK('\t') ||
  FPUTCSV_FLD_CHK(' ')
)

没有“始终包含”选项。

我需要创建一个包含每个字段的 CSV 文件...最好的解决方案是什么?

提前谢谢...

【问题讨论】:

  • 可以选择更改 php 源吗? IE。在您的情况下,在函数参数中添加一些“始终包含”标志是否可行?

标签: php csv fputcsv


【解决方案1】:

滚动你自己的函数 - 不难:

 function dumbcsv($file_handle, $data_array, $enclosure, $field_sep, $record_sep)
 {
     dumbescape(false, $enclosure);
     $data_array=array_map('dumbescape',$data_array);
     return fputs($file_handle, 
         $enclosure 
         . implode($enclosure . $field_sep . $enclosure, $data_array)
         . $enclosure . $record_sep);
 }
 function dumbescape($in, $enclosure=false)
 {
    static $enc;
    if ($enclosure===false) {
        return str_replace($enc, '\\' . $enc, $in);
    }
    $enc=$enclosure;
 }

(以上是使用unix风格转义)

C.

【讨论】:

  • $file_handle, $data_array, $enclosure, $field_sep, $record_sep - 你能举例说明什么是需要传递的值......请......提前谢谢你
  • $file_handle 需要为这个变量@symcbean 传递什么值
  • return fputs($file_handle, $enclosure . implode($enclosure . $field_sep . $enclosure, $data_array) . $enclosure . $record_sep);我在这行消息中收到错误:数组到字符串转换
【解决方案2】:

解决方法:假设您的数据在二维数组中,您可以附加一个强制引用的字符串,并且您确定不包含在您的数据中(此处为“#@ @#”),然后将其删除:

    $fp = fopen($filename, 'w');
    foreach ($data as $line => $row) {
        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);

【讨论】:

    【解决方案3】:

    我也遇到了同样的问题,我已经解决了如下。
    我在每个数组值中插入了单引号。
    这样当你用excel打开csv文件时,科学计数法E+15就不再显示了。

    在这里我和你一样。

    这对我有用,我希望你也这样做。
    问候

            // this function add a single quote for each member of array
             function insertquote($value) {
                return "'$value'";
            }
    
            # here i send each value of array 
            # to a insertquote function, and returns an array with new values, 
            # with the single quote.
    
            foreach ($list as $ferow) {
                fputcsv($fp, array_map(insertquote, $ferrow), ';');
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 2010-10-21
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      相关资源
      最近更新 更多