Reputation: 3171
I have a CSV like so:
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL! ""TODAY""
air, moon roof, loaded",4799.00
How can I convert it into a 2-dimensional array without the last line getting misplaced into its own array?
Here is the illustration of the problem (also hosted here https://3v4l.org/HAJh1):
$s2=<<<EOD
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL! ""TODAY""
air, moon roof, loaded",4799.00
EOD;
$lines=str_getcsv($s2,"\n");
print_r($lines);
And the bug in question (despite the PHP devs not recognizing it as one as of this writing): https://bugs.php.net/bug.php?id=55763
There are "solutions" out there, but none which seems to address this example.
Upvotes: 1
Views: 201
Reputation: 780974
str_getcsv()
expects the string to be one CSV record, not the entire CSV file.
If you have the CSV file in memory, you can use php://memory
to turn it into a stream that you can read with fgetcsv()
. This will properly parse the records.
<?php
$s2=<<<EOD
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL! ""TODAY""
air, moon roof, loaded",4799.00
EOD;
$stream = fopen("php://memory", "r+");
fwrite($stream, $s2);
rewind($stream);
while ($row = fgetcsv($stream)) {
print_r($row);
}
If the CSV is actually in a file, just open the file and use fgetcsv()
to read it as in the above.
Upvotes: 1