How to read and write an entire file

Three functions to read an entire file

Function Description
file($name) Description Returns an array with each element containing one line from the file.
file_get_contents($name) Returns the contents of the file as a string.
readfile($name) Reads a file and echoes it to the web page.

A function to write an entire file

Function Description
file_put_contents($name, $data) Writes the specified data string.

How to read and write text

Read text from a file

      $text = file_get_contents('message.txt');
      $text = htmlspecialchars($text); 
      echo("<div>$text</div;>");

      

Write text to a file

      $text = "This is line 1.\nThis is line 2.\n"; 
      file_put_contents('message.txt', $text);
      

How to read and write arrays

Read a file into an array

      $names = file('usernames.txt'); 
      foreach ($names as $name) { 
        echo("<div>$name</div;>");
      }
      

Write an array to a file

      $names = array('joelmurach', 'rayharris', 'mikemurach'); 
      $names = implode("\n", $names); 
      file_put_contents('usernames.txt', $names);
      

Description

Back