O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading and Writing Parts of Files

The file_get_contents( ) and file_put_contents( ) functions are fine when you want to work with an entire file at once. But when it's time for precision work, use other functions to deal with a file a line at a time. Example 10-6 reads a file in which each line contains a name and an email address and then prints an HTML-formatted list of that information.

Example 10-6. Reading a file a line at a time

$fh = fopen('people.txt','rb');
for ($line = fgets($fh); ! feof($fh); $line = fgets($fh)) {
    $line = trim($line);
    $info = explode('|', $line);
    print '<li><a href="mailto:' . $info[0] . '">' . $info[1] ."</li>\n";
}
fclose($fh);

If people.txt contains what's listed in Example 10-7, then Example 10-6 prints:

<li><a href="mailto:alice@example.com">Alice Liddell</li>
<li><a href="mailto:bandersnatch@example.org">Bandersnatch Gardner</li>
<li><a href="mailto:charles@milk.example.com">Charlie Tenniel</li>
<li><a href="mailto:dodgson@turtle.example.com">Lewis Humbert</li>

Example 10-7. people.txt for Example 10-6

alice@example.com|Alice Liddell
bandersnatch@example.org|Bandersnatch Gardner
charles@milk.example.com|Charlie Tenniel
dodgson@turtle.example.com|Lewis Humbert

The four file access functions in Example 10-6 are fopen( ) , fgets( ) , feof( ), and fclose( ). The fopen( ) function opens a connection to the file and returns a variable that's used for subsequent access to the file in the program. (This is very similar to the database connection variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required