Ritesh
Ritesh

Reputation: 11

fgetcsv is not splition data properly

i am importing csv file to upload data into database. But in some products the description is not going through properly. the description is like

TSD/UHC Model UG-132, 6\" gas revolver with plastic shells. Shells: MUG131 & MUG131BRASS. 290-320 FPS with .20g BBS.

Legal Disclaimer

Restrictions: You must be 18 or older to order this product. In some areas, state and local laws further restrict or prohibit the sale and possession of this product. In ordering this product, you certify that you are at least 18 years old and satisfy your jurisdiction\'s legal requirements to purchase this product.

Warning: This product may be mistaken for a firearm by law enforcement officers or others, and altering its color or brandishing the product in public may be considered a crime.

but when i print fgetcsv array it display this description in different array like.

[2] => TSD/UHC Model UG-132, 6\" gas revolver with plastic shells. Shells: MUG131 & MUG131BRASS. 290-320 FPS with .20g BBS. Legal Disclaimer

Restrictions: You must be 18 or older to order this product. In some areas [3] => state and local laws further restrict or prohibit the sale and possession of this product. In ordering this product [4] => you certify that you are at least 18 years old and satisfy your jurisdiction\'s legal requirements to purchase this product.
Warning: This product may be mistaken for a firearm by law enforcement officers or others [5] => and altering its color or brandishing the product in public may be considered a crime.

"

I also have more products with this kind of description with backslash, single quot and double quot. some other products are uploaded properly but some are having problem.

Thanks

Upvotes: 1

Views: 576

Answers (3)

Zoltán Süle
Zoltán Süle

Reputation: 1694

I had a similar issue and tried many different ways but without preprocessing and cleaning the whole file this was the only working solution:

$handle = fopen($filepath, "r");
if ($handle === false) {
    throw new someException('fopen error');
}

$rowNumber = 1;
while (($data = fgetcsv($handle, 0, ',', '"', "\0")) !== false) {
    yield $rowNumber => $data;
    $rowNumber++;
}
fclose($handle);

I have found the working solution here: https://stackoverflow.com/a/46342634/5356216

More details with code and example data: https://stackoverflow.com/a/74721279/5356216

Upvotes: 0

Nirav Patel
Nirav Patel

Reputation: 11

fgetcsv($handle, 0, ",", '"', '""');

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212402

Try

fgetcsv($handle, 0, ",", '"', '\\');

which use a comma (,) as a separator, unless it's part of a field wrapped in "; and if " appears as a character in the field it must be escaped with a \

If a comma isn't the separator, then you'll need to use the appropriate separator character

Upvotes: 0

Related Questions