Search code examples
phpcsvfgetcsv

How to parse a CSV file using PHP


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?


Solution

  • Just use the function for parsing a CSV file

    http://php.net/manual/en/function.fgetcsv.php

    $handle = fopen("test.csv", "r");
    while (($row = fgetcsv($handle)) !== FALSE) {
        // do something with row values
        print_r($row);
    }
    fclose($handle);
    

    Note that this method correctly handles values even if they contain quotes or line breaks.

    In case your CSV file uses different delimiter, value enclosure or escape characters, you can configure them in the fgetcsv() function's parameters.