Parsing CSV files with PHP – SPL-Style

There are some CSV (Comma Separated Values) related string and file functions in PHP. But when it comes to deal with CSV files, there is another gem: SplFileObject (PHP Manual) built-in. The class makes it even more easy to iterate over the rows. A short example:

<?php
/**
 * open csv file and iterate over rows
 */

$file = 'data.csv';
try {
	$csv  = new SplFileObject($file, 'r');
} catch (RuntimeException $e ) {
	printf("Error openning csv: %s\n", $e->getMessage());
}

while(!$csv->eof() && ($row = $csv->fgetcsv()) && $row[0] !== null) {
	// $row is a numelrical keyed array  with
	// a string per each field (zero based).
}
?>

If your file has a last empty row, the class’s fgetcsv() function returns it as an array containing one element with the NULL value.

The object itself is handy for file related operations and using it prevents you to deal with fopen, close etc. separately. It support streams like it’s common in PHP and you can set options for the CSV format as well (seperator etc.).

By default PHP is compatible with standard CSV files, for example with those exported from the Calc Spreadsheet application of the OpenOffice.org office suite – both do a worry free working together.

Read On:

This entry was posted in Hakre's Tips, Pressed and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Parsing CSV files with PHP – SPL-Style

  1. filosofo says:

    I didn’t realize SplFileObject had CSV-specific methods. That’s very helpful to know, thanks!

    • hakre says:

      I was not aware either. Reading is a bliss, writing is not possible as of now. Works like a charm for quick and easy CSV integration for me so far. I added some links to more ways of use btw.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s