【问题标题】:Parsing CSV in PHP and trying to keep line breaks in field contents在 PHP 中解析 CSV 并尝试在字段内容中保留换行符
【发布时间】:2014-08-09 15:14:33
【问题描述】:

我有一个 csv 文件,其中一列有换行符。该列是一个描述字段,因此它存储文本行、项目符号点和最重要的换行符——有时在段落之间有两个。更复杂的是,描述字段还包含引号。

我已经尽我所能将内容(并保持格式)放入变量中。我试过 file_get_contents、str_getcsv 和 fgetcsv 无济于事。其中一个函数让我将整个描述字段放入一个变量中,但它删除了所有新行,因此所有内容都在一个巨大的段落中。另一个单独解析描述字段中的每个段落,而不是一个单元。

这是我的 csv 文件的一般格式:

"391","The Great Gatsby","The Great Gatsby, F. Scott Fitzgerald’s third book, stands as the supreme achievement of his career. 

This exemplary novel of the Jazz Age has been acclaimed by generations of readers. The story of the fabulously wealthy Jay Gatsby and his love for the beautiful Daisy Buchanan, of lavish parties on Long Island at a time when The New York Times noted “gin was the national drink and sex the national obsession,” it is an exquisitely crafted tale of America in the 1920s.

The Great Gatsby is one of the great classics of twentieth-century literature.","No","Yes",

我想要一个变量,其中$array[0]=391、$array[1]=The Great Gatsby 和最重要的$array[2] 包含描述中的文本以及所有换行符和格式,包括字段本身中的引号。

或者如果有更好的方法来使用 PHP 解析这个,请告诉我。

【问题讨论】:

  • 你试过nl2br
  • 不,我现在去看看
  • fgetcsv() 应该正确读取;但是换行符不会显示在网络浏览器中,除非您将文本包装在 或 <code> 标签中,或者在显示之前使用 nl2br()</code>
  • 目前,我不想让它在网络浏览器中显示。我正在尝试将其转储到数据库中并保持格式相同。 fgetcsv 是单独解析描述字段的每一行而不是一个单元。
  • 您在显示数据时使用它,而不是在阅读时使用它......echo nl2br($comments); - 请参阅PHP docs

标签: php csv


【解决方案1】:

如果有人在 2019 年仍然遇到此问题,我的解决方案是 fgetcsv($file)。自动遵守文本字段内的换行符。

【讨论】:

    【解决方案2】:

    我最近自己为这个用例编写了一个函数。

    PHP 函数str_getcsv() 用于解释单个行 CSV 数据。通常,您可以简单地将文件分解为新行,然后单独解析每一行,但是当字段本身可能包含新行时,您会怎么做?

    诀窍是使用str_getcsv()两次:一次将文件拆分为行,然后再次拆分每个单独的行。

    /**
     * Receives CSV string and returns as an array.
     *
     * *************************************************************************
     *
     * Based on code by fab at tradermail dot info at http://php.net/manual/en/function.str-getcsv.php#119666
     */
    function csv_to_array($csv, $delimiter=',', $header_line=true) {
        // CSV from external sources may have Unix or DOS line endings. str_getcsv()
        // requires that the "delimiter" be one character only, so we don't want
        // to pass the DOS line ending \r\n to that function. So first we ensure
        // that we have Unix line endings only.
        $csv = str_replace("\r\n", "\n", $csv);
    
        // Read the CSV lines into a numerically indexed array. Use str_getcsv(),
        // rather than splitting on all linebreaks, as fields may themselves contain
        // linebreaks.
        $all_lines = str_getcsv($csv, "\n");
        if (!$all_lines) {
            return false;
        }
    
        $csv = array_map(
            function(&$line) use ($delimiter) {
                return str_getcsv($line, $delimiter);
            },
            $all_lines
        );
    
        if ($header_line) {
            // Use the first row's values as keys for all other rows.
            array_walk(
                $csv,
                function(&$a) use ($csv) {
                    $a = array_combine($csv[0], $a);
                }
            );
            // Remove column header row.
            array_shift($csv);
        }
    
        return $csv;
    }
    

    奖励:这个函数也可以(如果$header_line)返回一个关联数组,使用第一行作为键名。

    【讨论】:

      【解决方案3】:

      我最近在上传大量数据库时遇到了这个问题,所以我在循环中添加了一些代码。它检查标题字段计数是否与每次传递的字段计数匹配,如果不匹配,则从 fgetcsv 获取下一个数组,并继续直到它们与字段计数匹配。因此,如果您在任意数量的字段中有 100 个换行符,它们都将被保留。

      $file = fopen($filenam,"r");
      
      $count=0;
      
      while (($fields = fgetcsv($file,0,"|")) !== false) 
         
       {
          
                  $count++;
                  if($count == 1)  {
                      $sql_fields=[];$fc=0;
                      foreach($fields as $field) {
                          //$sql_fields .= $field.",";
                          $sql_fields[] = $field;
                          $fc++;
                      }
                      continue;
                  }
                  
                  if(count($fields)!=$fc) {
                      if($gotprev!='') {
                          $gotprev .= implode("|",$fields);
                          $fields = explode("|",$gotprev);
                          if(count($fields)!=$fc)
                              continue;
                          $gotprev='';
                      }else{
                           $gotprev = implode("|",$fields);
                           continue;
                      }    
                      
                  }
                  
                  $sql_values='';$rc=0;$sql_fields_gen='';
                  foreach($sql_fields as $key=>$field) {
                         
                      if($fields[$key]=='False') $fields[$key]=0;
                      if($fields[$key]=='True') $fields[$key]=1;
                      $sql_values .= "'".addslashes($fields[$key])."',";
                      $rc++;
                      $sql_fields_gen .= $field.",";
                  }
                      
                  
                  $sql_fields_gen = "(".rtrim($sql_fields_gen,",").")";
                  $sql_values = "VALUES (".rtrim($sql_values,",").")";
                  $sql_insert = "INSERT INTO mytable $sql_fields_gen $sql_values ";                
                  $DB->execute($sql_insert);           
      }
      

      【讨论】:

        猜你喜欢
        • 2012-07-19
        • 1970-01-01
        • 2011-03-24
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        • 2023-04-06
        • 2021-08-28
        • 1970-01-01
        相关资源
        最近更新 更多