Page 347 - Beginning PHP 5.3
P. 347
Chapter 11: Working with Files and Directories
This code displays:
Name: John Smith, Age: 45
Name: Anna Clark, Age: 37
Name: Bill Murphy, Age: 32
PHP 5.3 introduces a new function, str_getcsv(), that reads CSV data from a string instead of from
a file. This is handy if you already have your CSV data in memory. For details see http://www.php
.net/manual/en/function.str-getcsv.php.
Reading and Writing Entire Files
Writing code to read a file line by line, or string by string, can be tedious. Fortunately, PHP provides you
with some functions that can access the complete contents of a file in one go. These include:
❑ file() — For reading a whole file into an array, without needing to open it
❑ file_get_contents() and file_put_contents() — For reading and writing the contents of
a file without needing to open it
❑ fpassthru() — For displaying the contents of an open file
❑ readfile() — For displaying the contents of a file without needing to open it
Because these functions read the entire file into memory in one go, they should really be used for
relatively small files (a few MB at most). If you ’ re working with a 100MB text file, it ’ s probably best to
use fread() or fgets() to read and process the file in chunks.
file() reads the contents of a file into an array, with each element containing a line from the file. It
takes just one argument — a string containing the name of the file to read — and returns the array
containing the lines of the file:
$lines = file( “/home/chris/myfile.txt” );
The newline character remains attached at the end of each line stored in the array.
This function, like most of the others described in this section, doesn ’ t require you to specify a file
handle. All you need to do is pass in the filename of the file to read. The function automatically opens,
reads, and, once it ’ s done, closes the file.
You can optionally specify some useful flags as the second parameter to file() :
Flag Description
FILE_USE_INCLUDE_PATH Look for the file in the include path (see Chapter 20 for more on
include paths)
FILE_IGNORE_NEW_LINES Remove newline characters from the end of each line in the array
FILE_SKIP_EMPTY_LINES Ignore empty lines in the file
309
9/21/09 9:10:14 AM
c11.indd 309 9/21/09 9:10:14 AM
c11.indd 309