Wikis & learning

Read CSV rows with quoted punctuation

CSV fields can contain commas and doubled quotes. Splitting every line on a comma can separate one title into multiple fields.

CSV fields can contain commas and doubled quotes. Splitting every line on a comma can separate one title into multiple fields.

Walkthrough

fgetcsv interprets field boundaries. Passing an empty escape argument makes the treatment of doubled quotes explicit. Work with the parsed fields before choosing their display format.

PHP example

<?php
$stream = fopen('php://temp', 'w+');
fwrite($stream, "17,\"Notes, revised\",3\n");
rewind($stream);
[$id, $title, $qty] = fgetcsv($stream, 0, ',', '"', '');
fclose($stream);
echo $id, ' / ', $title, ' / ', $qty;

Expected output

17 / Notes, revised / 3

Change and check

Add a second row whose title contains doubled quotation marks. Read it with a loop and confirm that the title is returned as one field.