【问题标题】:PHP: Parse .csv file with line breaks in field value (partly quoted)PHP:解析 .csv 文件,字段值中有换行符(部分引用)
【发布时间】:2016-09-13 11:55:20
【问题描述】:

已经有一些关于这个主题的问题,但是我还没有找到令人满意的答案。虽然常见的 .csv 阅读器软件(例如 Libre Office)可以毫无问题地读取文件,但 PHP 对此有问题。

文件的示例部分:

86010800,class,Table Games,,"(10005183, 10005184, 10005185)"
86011100,class,Toy Vehicles – Non-ride,,"(10005192, 10005190, 10005191, 10005193, 10005194, 10005195, 10005196)"
86011000,class,Toys – Ride-on,,"(10005187, 10005188, 10005441, 10005189)"
86010900,class,Toys/Games Variety Packs,,(10005186)
10001686,brick,Airbrushes (Powered),"Definition:
 Includes any products that can be described/observed as a powered 
machine that scatters paint using air pressure and which is used for 
design illustrations, fine art and delicate fine spray applications. The
 machine comprises of a compression or propulsion device to scatter the 
paint.Specifically excludes Spray Paint and Aerosols.Excludes Airbrushing Replacement Parts and Accessories such as Airbrush Control Valves and Airbrush Hoses.",()
10001688,brick,Airbrushing Equipment – Replacement Parts/Accessories,Definition: Includes any products that can be described/observed as a replacement part/accessory for airbrushing equipment.Includes products such as Airbrush Control Valves and Airbrush Hoses.Excludes products such as complete Airbrushes.,(20001349)
10001690,brick,Airbrushing Supplies Other,"Definition:
 Includes any products that may be described/observed as Airbrushing 
Supplies products, where the user of the schema is not able to classify 
the products in existing bricks within the schema.Excludes all currently classified Airbrushing Supplies.",()

如您所见,第 4 列和第 5 列被部分引用,因为它们可能包含换行符,简单值没有被引用。

我想要的是一个二维数组,其中一行是 1 级,该行的五列是 2 级。

我试过了

fgetcsv()

解析多行字段失败和

str_getcsv()

无法使用正确的参数解析二维。如何用 PHP 正确解析这个 .csv 文件?

【问题讨论】:

标签: php csv parsing delimiter multiline


【解决方案1】:

希望 SplFileObject::fgetcsv() 帮助您解析 CSV 文件。在下面提到的链接中已经给出了示例,因此请使用该链接并检查其是否正确获取。 http://php.net/manual/en/splfileobject.fgetcsv.php

编辑:完整代码示例

$file = new SplFileObject('../../temp/file.csv');
$ar = array();
while (!$file->eof()) {
    array_push($ar,$file->fgetcsv());
}
echo '<pre>';
print_r($ar);
echo '</pre>';
die;

【讨论】:

  • 感谢原生 PHP 解决方案。
猜你喜欢
  • 2020-05-02
  • 2017-01-23
  • 2022-01-27
  • 2011-07-12
  • 2013-03-09
  • 2019-02-18
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
相关资源
最近更新 更多