繁体   English   中英

php文件中显示的CSV文件中的引号而不是环绕字段

[英]Quote marks in CSV file displayed in php file instead of wrapping field

我有一个PHP文件,该文件从CSV文件中提取信息,并将其成功转换为仅显示特定行和列的表。

但是,CSV文件中包含带引号的逗号和空格的条目。 由于逗号,我的PHP文件将这些条目分为两部分,并显示引号而不是使用引号表示这是一个包含逗号和空格的字段。

例如,CSV文件如下所示:

AA,BB,"Surname, Initial",CC,DD,EE

“姓氏和名字首字母”应该在结果表的同一字段中,但是将创建两个字段。

我真的很想在PHP代码中解决此问题,而不是通过修改CSV文件本身来解决。 代码在这里:

echo "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>
      <link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\">";
$file = 'CSV/test.csv';   
$lines = file($file);
if (file_exists($file)){
  //echo "$file exists<br/>"; 

echo '<table>';                     //create the html table
$x=2;       //define the first line to display
$y=20;       //define the last line to display
$line_counter=0;
foreach ($lines as $line) {         //loop to fill your table with csv data
  if($x<=$line_counter && $line_counter<=$y)
  {
    $expl = explode(",", $line);      //explode each line on "," to create the rows
    echo "<tr>";                      //create each line of your table
    $c=0;
    while ($c<=47) {                  //loop to extract columns 2 to 47
      if(($c % 2) == 1){              //odd  rows
        echo "<td class=\"odd\">".$expl[$c]."</td>";
      }
      elseif(($c == 0)){
        echo "<td class=\"even\">".$expl[$c]."</td>";
      }
      else{
        echo "<td class=\"even\">".$expl[$c]."</td>";    //even rows
      }
      $c++;
    }
    echo "</tr>";
    $x++;
  }
  $line_counter++;
}
echo "</table>";
}

内置的fgetcsv()函数应处理任何正确的CSV格式。 它具有可以更改定界符和预期报价类型的参数。 如果CSV没有损坏,则此函数应该可以对其进行解析。 尝试将其交换为自己的解析器,根据需要调整CSV格式的参数,然后循环遍历所得数组。

http://www.php.net/manual/en/function.fgetcsv.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM