How To: Read a CSV in PHP
February 23, 2010
Reading a CSV in PHP is much easier than I anticipated with the advent of the fgetcsv() function for PHP 4. The function basically reads a file line by line and performs and explode on the delimiter, returning the array. Here’s some sample code:
$length = 0;
if ( ($handle = @fopen($file, "r")) !== FALSE )
{
while (($row = fgetcsv($handle, $length, "\t")) !== FALSE)
{
var_dump($row); //dumps an array corresponding
}
}
The length parameter is option as of PHP 5.0.4. Using a limited line length makes execution slightly faster, so if it is realistic to limit line length (even if limiting it at a great value) it could improve script execution time significantly.
The function also allows for setting the enclosure and escape characters.