Prev | Current Page 353 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Consider the following sample text file named
users.txt:
Ale ale@example.com
Nicole nicole@example.com
Laura laura@example.com
The following script reads in users.txt and parses and converts the data into a
convenient Web-based format. Notice file() provides special behavior because
unlike other read/write functions, you don??™t have to establish a file handle in order to
read it:
// Read the file into an array
$users = file("users.txt");
// Cycle through the array
foreach ($users as $user) {
// Parse the line, retrieving the name and e-mail address
list($name, $email) = explode(" ", $user);
// Remove newline from $email
$email = trim($email);
// Output the formatted name and e-mail address
echo "$name
";
}
?>
CHAPTER 10 ?–  WORKING WITH T HE FILE A ND OPERATING SYSTEM 291
This script produces the following HTML output:
Ale

Nicole

Laura

Like fopen(), you can tell file() to search through the paths specified in the
include_path configuration parameter by setting use_include_path to 1. The context
parameter refers to a stream context. You??™ll learn more about this topic in Chapter 16.
Reading File Contents into a String Variable
The file_get_contents() function reads the contents of a file into a string.


Pages:
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365