Page 346 - Beginning PHP 5.3
P. 346
Part III: Using PHP in Practice
The code produces the following output:
1: The mind is its own place, and in it self
2: Can make a Heav’n of Hell, a Hell of Heav’n.
3: What matter where, if I be still the same,
Reading CSV Files
If you ’ ve ever done any work with importing and exporting data, you probably know about the comma -
separated - value (CSV) data format. (CSV even has its own file extension: .csv .) In CSV files, each data
record sits on its own line, and the fields within each record are separated by commas. String values are
often enclosed within double quotes:
“John”,”Smith”,45
“Anna”,”Clark”,37
“Bill”,”Murphy”,32
To read CSV files, you can use fgetcsv() . This function reads a line of CSV - formatted data from an
open file starting from the position of the file pointer, and puts the data it finds into an array, with one
field value per array element. Once you have an array of data you can easily manipulate it.
To call the fgetcsv() function, pass it the file handle of an open file. You can also optionally specify:
❑ The maximum number of characters to read. You can leave this value out, or use 0, in which case
PHP reads as many characters as necessary to read the whole line. However, specifying a value
makes the function slightly quicker
❑ The delimiter that is used to separate each data value. The default is the comma ( , ). If you ’ re
reading a tab - separated - value (TSV) file, specify “ \t ” (the tab character) for this argument
instead
❑ The character that is used to enclose string values. The default is the double quote ( “ )
❑ The character used to escape special characters. The default is the backslash ( \ )
fgetcsv() returns false if there was a problem reading the line, or if the end of the file has been
reached.
The following code snippet shows how you might retrieve three lines of data from a file in CSV format:
/*
people.csv contains:
“John”,”Smith”,45
“Anna”,”Clark”,37
“Bill”,”Murphy”,32
*/
$handle = fopen( “people.csv”, “r” );
while ( $record = fgetcsv( $handle, 1000 ) ) {
echo “Name: {$record[0]} {$record[1]}, Age: {$record[2]} < br / > ”;
}
fclose( $handle );
308
9/21/09 9:10:14 AM
c11.indd 308 9/21/09 9:10:14 AM
c11.indd 308