How to parse a CSV file using PHP
401,277
Solution 1
Just use the function for parsing a CSV file
http://php.net/manual/en/function.fgetcsv.php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Solution 2
A bit shorter answer since PHP >= 5.3.0:
$csvFile = file('../somefile.csv');
$data = [];
foreach ($csvFile as $line) {
$data[] = str_getcsv($line);
}
Solution 3
Handy one liner to parse a CSV file into an array
$csv = array_map('str_getcsv', file('data.csv'));
Solution 4
Just discovered a handy way to get an index while parsing. My mind was blown.
$handle = fopen("test.csv", "r");
for ($i = 0; $row = fgetcsv($handle ); ++$i) {
// Do something will $row array
}
fclose($handle);
Source: link
Solution 5
I love this
$data = str_getcsv($CsvString, "\n"); //parse the rows
foreach ($data as &$row) {
$row = str_getcsv($row, "; or , or whatever you want"); //parse the items in rows
$this->debug($row);
}
in my case I am going to get a csv through web services, so in this way I don't need to create the file. But if you need to parser with a file, it's only necessary to pass as string
Related videos on Youtube
Author by
smith
Updated on June 05, 2021Comments
-
smith almost 3 years
Suppose I have a
.csv
file with the following content:"text, with commas","another text",123,"text",5; "some without commas","another text",123,"text"; "some text with commas or no",,123,"text";
How can I parse the content through PHP?
-
quickshiftin over 12 yearsYou're basically asking if there is a better OOP way to deal w/ CSV parsing than the stock global function approach. I'd say reword the question, as this does not sound like an issue parsing a CSV really.
-
smith over 12 years@quickshiftin sorry about that
-
quickshiftin over 12 yearsIt's fine, I'm just saying... If you want a class this one is OK (I've tweaked it a bit in my work tho..)
-
-
amenthes over 8 yearsit should be noted that this function does not correctly deal with quotes in CSV. Specifically, it can't deal with this example as found in wikipedia: en.wikipedia.org/wiki/Comma-separated_values#Example there has been an open bug, but it has been closed as "wont fix" bugs.php.net/bug.php?id=50686
-
Jordan Lev over 8 yearsNote that this doesn't work if you have any newlines in the actual values (not the line delimiters at the end of each csv line), because the
file
function splits on newlines and isn't aware of the quotation marks that CSV uses to contain field values. -
Jordan Lev over 8 yearsNote that this doesn't work if you have any newlines in the actual values (not the line delimiters at the end of each csv line), because the
file
function splits on newlines and isn't aware of the quotation marks that CSV uses to contain field values. -
sdd about 7 yearsHow to use different delimiter? ( ; instead of , )
-
Benjamin about 7 yearsOur server had PHP 5.2.9 and I am unable to access str_getcsv because of that. fgetcsv on the other hand dates all the way to PHP 4, so this was helpful. Thanks.
-
Julix about 7 years@JordanLev so what do you recommend then?
-
Jordan Lev about 7 years@Julix use the accepted answer . This shorter version is nice if you know the imported data will never have linebreaks within a single value, but otherwise the more robust solution is worth the extra lines of code.
-
Julix about 7 yearsI ended up encoding before saving to CSV and decoding while reading - php.net/rawurlencode - that ensures no line-breaks, right? - or does it loose them entirely (can there be line breaks in URL encoding?)
-
Robert Sinclair almost 7 yearsuse the following to fix new line problem: array_map('str_getcsv', file('data.csv' , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
-
xZero almost 7 yearsYou know, it is nice to give credits to respective authors: php.net/manual/en/function.str-getcsv.php#114764
-
Madhab452 almost 7 yearsThis answer perfectly works for new line and uses the magic of php file function. Thanks
-
Krishna Jonnalagadda about 6 years@Maxim Kovalevsky, how to skip heading or first line
-
confetti about 4 yearsThis might be obvious to others, but I just spent two hours trying to figure out what's wrong with PHP when my string quote was set to
'
. Make sure it's"
, then this and other scripts will work. -
obe almost 4 yearsThis didn't work correctly for me. For example, this:
aaa,bbb,"ccc\nddd",eee
was parsed into two lines (instead of the desired one line) instead of one. It seems that"
is not recognized as enclosure when it appears inside the field (rather than in its beginning or end). So$data = str_getcsv(..)
can be replaced with$data = explode(..)
, which I'm guessing is more efficient, and conveys intention better... -
DanimalReks over 3 yearsThis is excellent unless one has very large files.
-
Valerie over 3 yearsJust wondering why a for loop was used instead of a while loop?
-
quartarian over 3 years@valerie I almost always need an index while parsing CSVs. The for loop provides the index without a separate declaration and incrementer.
-
Professorval almost 3 yearsDoes not work correctly on columns with line breaks in their content too