Logo         Community
The Company
Your Account
Contact Us
PHP 101 (part 5): Rank And File
Learn how to read and write files with PHP.

| Different Strokes |

An alternative method of reading data from a file is the very cool file() function, which reads the entire file into an array (remember them?) with one line of code. Each element of the array then contains one line from the file. To display the contents of the file, simply iterate over the array in a foreach() loop and print each element.

The following example demonstrates:


// set file to read
$file = '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt';
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line) {
    echo $line;


In this example, the file() command opens the file, reads it into an array and closes the file - all in one, single, elegant movement. Each element of the array now corresponds to a line from the file. It's easy to print the file's contents now - just reach for that mainstay of array processing, the foreach() loop.

Don't want the data in an array? Try the file_get_contents() function, new in PHP 4.3.0 and PHP 5.0, which reads the entire file into a string:


// set file to read
$file = '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt';
// read file into string
$data = file_get_contents($file) or die('Could not read file!');
// print contents
echo $data;


Who am I kidding? I always use the one-line functions noted above instead of the three-line sequence of fopen(), fread() and fclose(). Laziness conquers all.

How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!

previous page more like this  print this article  next page
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
In cut!...
American Chai
The Core
Find out how you can use this article on your own Web site!

Copyright © 1998-2018 Melonfire. All rights reserved
Terms and Conditions | Feedback