Blackbam Blackbam - 2 months ago 19
PHP Question

PHP: Parse .csv file with line breaks in field value (partly quoted)

There are some questions on this topic already however I did not find a satisfying answer yet. While common .csv reader software (e.g. Libre Office) can read the file without any problems PHP has problems with this.

Sample part of the file:

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.",()


As you can see column 4 and column 5 are partly quoted as they may contain line breaks, simple values are not quoted.

What I want is a 2-dimensional array where a row is level 1 and the five columns of the row are level 2.

I have tried


fgetcsv()


which fails parsing the multiline fields and


str_getcsv()


which fails parsing in two dimensions both with the correct parameters. How to parse this .csv-file best correctly with PHP?

Answer

Hope SplFileObject::fgetcsv() helps you to parse the CSV file. In below-mentioned link the example is already given, so use that and check its get fetched properly or not. http://php.net/manual/en/splfileobject.fgetcsv.php

Edit: Full code sample

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