php fputcsv和封闭字段

问题描述 投票:8回答:3

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

问题是

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

例如,您可能最终得到一个这样的行

11,“ Bob”,Jenkins,“美国主街200号“等

将伪造的空格附加到每个领域的尽头,有没有强制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 csv fputcsv
3个回答
8
投票

滚动您自己的功能-不难:

 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。


1
投票

一种解决方法:假设您的数据位于二维数组中,则可以附加一个字符串,该字符串将强制使用引号,并且确保您的数据中没有包含该字符串(此处为“#@ @#”),然后将其删除:

    $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);

0
投票

我遇到了相同的问题,并且已经按照以下方法解决了。我已经为每个数组值插入了单引号。这样,当您使用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), ';');
        }
© www.soinside.com 2019 - 2024. All rights reserved.