PHP Phrasebook
Authors: Wenz Ch
Published year: 2005
Pages: 105-106/193
Buy this book on amazon.com >>

Reading from Files


echo file_get_contents(

'

file.txt

'

);



To read data from a file, PHP offers several possibilities. Probably the easiest way is to read it all at once and then output it to the user .

The function file_get_contents() , available since PHP 4.3.0, returns the contents of a file (or stream) as a string so that it all can be processed further. The preceding code reads in a file called file.txt and prints out its contents. This function is binary-safe, that's why no file mode can (or has to) be used.

The file() function works as file_get_contents() , but returns the file's contents as an array: Each element is one row in the file (including the line break character). The following code converts this array into a string and sends it to the browser. The function implode() glues the array element together (see Chapter 2, "Working with Arrays").

<?php
  echo implode('', file('file.txt'));
?>

An even shorter way is to use readfile() , which sends the file's contents directly to the browser. To be able to process the data before sending it, output buffering must be used. The following listing converts special Hypertext Markup Language (HTML) characters and uses <br> elements at line breaks so that the original content of the file is shown in the browser.

Sending a File's Contents to the Browser Using Output Buffering (readfile.php)
<?php
  ob_start();
  readfile('text.txt');
  $data = ob_get_contents();
  ob_end_flush();
  echo nl2br(htmlspecialchars($data));
?>

For maximum flexibility, the manual way can be used; however, for text files, this is often not needed. Open the file with fopen() , then call fgets() as long as data is returned (a while loop is convenient here) and output the data. fgets() returns as many characters as are provided in its second parameter but, at most, all characters until the end of the current line.

Sending a File's Contents to the Browser, Line-by-Line (readfile-linebyline.php)
<?php
  $fp = fopen('file.txt', 'r');
  while (!feof($fp)) {
    $line = fgets($handle, 4096);
    echo $line;
  }
  fclose($fp);
?>



Writing to Files


file_put_contents(

'

file.txt

'

,

''

> This text file contains\nsome random text.
<

''

);



Writing to files is as easy as reading from themif you are using PHP 5 or higher. Then, the function file_put_contents() writes data directly to a file, and this is binary-safe. After calling the function, the file is closed. The code writes data into a file.

Writing Data into a File (file_put_contents.php)
<?php
  file_put_contents('file.txt',
    ''> This text file contains\nsome random text.
      <'');
  echo 'File written.';
?>

However, the preceding code overwrites the existing file. If you want to append data (therefore emulating file mode a ), you first have to read in the file's data.

Appending Data to a File (file_append_contents.php)
<?php
  function file_append_contents($filename, $data) {
    $olddata = @file_get_contents($filename);
    return file_put_contents($filename,
      ''$olddata$data'');
  }

  file_append_contents('file.txt',
    "\n> This text file contains\neven more random
      text. <");
  echo 'Data appended to file';
?>

TIP

It is even easier to provide a third parameter to file_put_contents() to append data instead of overwriting files:

file_put_contents($filename, $data, FILE_
  APPEND);


However, this all fails when a PHP version below 5.0.0 is used because the function file_put_contents() does not exist in earlier versions. It is, however, possible to emulate the behavior of file_put_contents() for older PHP versions. This works similarly to reading from a file with fopen() , fgets() , and fclose() . For writing, just one more function is required: fwrite() writes data to a file handle. The following code implements this approach. Using function_exists() , you can check whether the function file_put_contents() already exists. If not, you can write it.

Using file_put_contents() with All Relevant PHP Versions (file_put_contents_compatible.php)
<?php
  if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $content)
      {
      if ($fp = @fopen($filename, 'w')) {
        $result = fwrite($fp, $content);
        fclose($fp);
        return $result;
      } else {
        return false;
      }
    }
  }

  file_put_contents('file.txt',
    "\n> This text file contains\nsome random text.
       <");
  echo 'Data written to file.';
?>


PHP Phrasebook
Authors: Wenz Ch
Published year: 2005
Pages: 105-106/193
Buy this book on amazon.com >>

Similar books on Amazon