1.10 Reading a Comma-Delimited Text File


You have data stored in a comma-delimited text file and you want to parse it.

Technique

Use the fgetcsv() function instead of the fgets() function when looping through the file:

 <?php $file_name = isset ($argv[0]) ? $argv[0] : "php://stdin"; $fp = @fopen ($file_name, "r")   or die ("Cannot open $file_name for read access"); while (!@feof ($fp)) {     $row = @fgetcsv ($fp, 1024, ',');     if (!is_array ($row)) {  continue; }     $rows[] = $row; } @fclose ($fp); ?> 

Comments

Parsing comma-separated data seems like an easy programming job ”just use PHP's explode() function to split the line by a comma, right? Wrong. Parsing comma-separated value (CSV) data is much more complex because the data stored in the CSV file often contains commas and, therefore, a pretty complex escaping system must be considered .

The fastest way to parse CSV data is to not parse it yourself, but rather to let PHP parse it for you with the fgetcsv() function. This works in any case in which you need to read data from a CSV file, but what about when you need to parse the data itself, without reading it line-by-line from a file?

The best solution is to create a temporary file using the tmpfile () function, write the data to that file, and then use the fgetcsv() function to read the data back in:

 <?php // $data contains the CSV data $tmp = @tmpfile()   or die ('Cannot create temporary file'); @fwrite ($tmp, $data); @fseek ($tmp, 0, SEEK_SET); while (!@feof ($tmp))_{     $row = @fgetcsv ($tmp, 1024, ',');     if (!is_array ($row)) {  continue; }     $rows[] = $row; } @fclose ($tmp); // $tmp is automatically deleted when the file is closed ?> 

This solution ”although it looks like (and is) a hack ”is much better than using a complex regular expression (which will also be a CPU hog) to parse the comma-separated data.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net