Categories
PHP

Reading a File into a String or Array

To read data from a file, PHP offers several possibilities. Probably the easiest way is to read it all at once with file_get_contents() function and then output it to the user or read it line by line with file() function.

Read entire file into a string

The function file_get_contents() returns the contents of a file (or stream) as a string so that it all can be processed further. The following 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:

<?php
 $text = file_get_contents( 'file.txt' );
 echo $text;

Example: Read the source of the web page of a website:

<?php
 $html = file_get_contents( 'https://brainbell.com/php/' );

The preceding code returns empty output if the directive allow_url_fopen is off in PHP’s ini configuration file.

Read entire file into an array

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, use FILE_IGNORE_NEW_LINES flag to remove the newline character at the end of each array element).

<?php
 $lines = file( 'file.txt' , FILE_SKIP_EMPTY_LINES);
 foreach ( $lines as $line ) {
  echo $line . '<br>';
 }

Example: Read a URL into an array:

<?php
 $lines = file( 'https://brainbell.com/php/' , FILE_SKIP_EMPTY_LINES);
 foreach ( $lines as $line ) {
  echo $line . '<br>';
 } 

file_get_contents() function

<?php
 //Syntax
 file_get_contents(
    string $filename,
    bool $use_include_path = false,
    ?resource $context = null,
    int $offset = 0,
    ?int $length = null
 ): string|false

The file_get_contents() function reads the entire content of a file into a string. Just pass the filename, and it returns a string containing everything in the file. This function accepts the following parameters:

  1. $filename: name of the file or URL to read.
  2. $use_include_path: (optional, default is false) assign true to search the include path if the file is not found.
  3. $context: (optional) can be null or a context resource.
  4. $offset: (optional) from where the reading starts, negative value count from the end of the file.
  5. $length: (optional) Maximum length of data read (default is the entire file).

Example: Reading a file or URL

<?php
 $text = file_get_contents('dir/file.txt');
 $html = file_get_contents('https://brainbell.com/php/');

Example: Read a portion of the file

<?php
 // Read entire file starting from the 21st character
 $txt = file_get_contents('file.txt', FALSE, NULL, 20);

 // Read 50characters starting from the 21st character
 $txt = file_get_contents('file.txt', FALSE, NULL, 20, 50);

Example: Sending a POST request with $context parameter

<?php
 // example.php
 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  echo 'User: '. $_POST['user'] . "\n";
  echo 'Pass: '. $_POST['pass'] . "\n";
  exit;
 }

 $url = 'http://localhost/example.php';
 $data = array('user' => 'brainbell', 'pass' => 'pwd');

 $options = array(
  'method'  => 'POST',
  'header'  => 'Content-Type: application/x-www-form-urlencoded',
  'content' => http_build_query($data)
 );
 
 // Create a context
 $context = stream_context_create(array('http' => $options));
 echo file_get_contents($url, false, $context); 

The preceding code prints the following output on the browser:

User: brainbell
Pass: pwd 

file() function

<?php
 //Syntax
 file(
    string $filename,
    int $flags = 0,
    ?resource $context = null
 ): array|false

The file() function returns an array in which each element corresponds to a line in the file. This function accepts the following parameters:

  1. $filename: name of the file or URL to read.
  2. $flags: (optional)
    • FILE_USE_INCLUDE_PATH: search the file in include path if not found.
    • FILE_IGNORE_NEW_LINES: by default the line break character includes at the end of each array entry, use this flag to omit the newline (line break) character.
    • FILE_SKIP_EMPTY_LINES: ignore empty lines (the output array will not contain any empty element).
  3. $context: (optional) a context resource.

Example: Read a file or URL into an array

<?php
 $fileArray = file ( 'file.txt' );
 $htmlArray = file ( 'https://brainbell.com/php/' ); 

The file() function preserves newline characters at the end of each array element. If you want to strip the newline characters, pass the constant FILE_IGNORE_NEW_LINES as the second argument to the function:

<?php
 $array = file('dir/file.txt', FILE_IGNORE_NEW_LINES);

You can also skip empty lines by using FILE_SKIP_EMPTY_LINES as the second argument:

<?php
 $array = file('dir/file.txt', FILE_SKIP_EMPTY_LINES);

To remove newline characters and skip empty lines, separate the two constants with a pipe sign:

<?php
 $array = file( 'dir/file.txt',
    FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );

Example: Sending a POST request with $context parameter

<?php
 // example.php
 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  echo 'User: '. $_POST['user'] . "\n";
  echo 'Pass: '. $_POST['pass'] . "\n";
  exit;
 }

 $url = 'http://localhost/example.php';
 $data = array('user' => 'brainbell', 'pass' => 'pwd');

 $options = array(
  'method'  => 'POST',
  'header'  => 'Content-Type: application/x-www-form-urlencoded',
  'content' => http_build_query($data)
 );
 
 // Create a context
 $context = stream_context_create(array('http' => $options));

 $array = file($url,FILE_IGNORE_NEW_LINES,$context);
 print_r($array); 

The preceding code prints the following output on the browser:

Array
(
    [0] => User: brainbell
    [1] => Pass: pwd
)

Working with Files in PHP: