PHP

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 Working 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

<?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

<?php
  $fp = fopen('file.txt', 'r');
  while (!feof($fp)) {
    $line = fgets($handle, 4096);
    echo $line;
  }
  fclose($fp);
?>

by BrainBellupdated
Advertisement: