PHP file() Function

Usage — The PHP file() function is used to read an entire file into an array. The contents of each line along with the newline character are stored in a different array element. This behavior is different from file_get_contents() which reads an entire file into a single string. You can also use file() to open remote files.

It has the following syntax:

PHP

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

Here is an example of using file():

PHP

/* Output —
Array
(
    [0] => Twinkle, twinkle, little star
    [1] => How I wonder what you are
    [2] => Up above the world so high
    [3] => Like a diamond in the sky
) */
print_r(file("poem.txt"));

Return Value — This function returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Additional Information — Please note that each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

PHP Version and Changelog — The file() function is available in PHP 4, PHP 5, PHP 7. It became binary-safe in PHP 4.3.0.

Relevant Functions — Other related PHP functions that you should know about are: readfile() which outputs a file, fopen() which opens file or URL, fsockopen() which opens Internet or Unix domain socket connection, popen() which opens process file pointer, file_get_contents() which reads entire file into a string, include which includes a given file and stream_context_create() which creates a stream context.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

filename

The filename parameter is used to specify path to the file. A URL can be used as a filename with this function if the fopen wrappers have been enabled. This is a required parameter.

flags

The flags parameter is used to specify some flag values that determine how the file should be handled. This is an optional parameter. It have have one or more of the following flags as its value:

  • FILE_USE_INCLUDE_PATH - This flag will search for the file in the include_path.
  • FILE_IGNORE_NEW_LINES - This flag will tell the function not to add newline at the end of each array element.
  • FILE_SKIP_EMPTY_LINES - This flag will tell the function to skip empty lines.

This is an optional parameter. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL.

context

The context parameter is used to specify a context resource created with the stream_context_create() function. Context is a set of options that can modify the behavior of a stream. It can be skipped by using NULL. This is an optional parameter. Context support was added with PHP 5.0.0.

Working Examples

Here are some examples of using the file() function:

PHP

$lines = file('http://www.example.com/');

foreach ($lines as $line_num => $line) {
    echo "Line $line_num : " .htmlspecialchars($line) . "\n";
}

$html = implode('', file('http://www.example.com/'));
 

The first file() example shows how go through HTTP to get the HTML source of a URL. Then it loops through the HTML source line by line and outputs it all along with line numbers. You can also use implode() along with file() to get the file contents as a string.

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. To write all the lines of the file one by one. In other words, to read the file line by line you can write the code like this:

    PHP

    $names=file('name.txt');
    
    foreach($names as $name) {
        echo $name.'<br>';
    }
    

    This example is so basic to understand how it’s working. I hope it will help many beginners.

    Suggested by - bingo at dingo dot com

  2. This may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my "c:\" drive. How do I file() it? Don’t forget the backslash is special and you have to “escape” the backslash i.e. "\\":

    PHP

    $lines = file("C:\\Documents and Settings\\myfile.txt");
    
    foreach($lines as $line) {
        echo($line);
    }
    

    Suggested by - d basin

  3. If the file you are reading is in CSV format do not use file(), use fgetcsv(). This is because file() will split the file by each newline that it finds, even newlines that appear within a field (i.e. within quotations).

    Suggested by - Martin K.

Further Reading

  1. You can read more about the PHP file() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top