Backend Development 3 min read

PHP file() Function: Reading Files into an Array

The PHP file() function reads an entire file into an array, offering optional flags to control path lookup, line handling, and context usage, with examples showing how to display lines, concatenate content, and apply flag combinations for flexible file processing.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP file() Function: Reading Files into an Array

The PHP file() function reads an entire file into an array, where each line becomes an element; optional flags control behavior such as including the path, ignoring new lines, or skipping empty lines, and a context resource can be provided.

Parameters: $filename (string path or URL), optional $flags (bitmask of FILE_USE_INCLUDE_PATH , FILE_IGNORE_NEW_LINES , FILE_SKIP_EMPTY_LINES ), and optional $context (resource for stream context).

Return value: an array of lines from the file, or false on failure.

Example usage:

$line) {
    echo "Line #
{$line_num}
: " . htmlspecialchars($line) . "
\n";
}

// Read a web page into a string
$html = implode('', file('http://www.example.com/'));

// Read a file while ignoring new lines and skipping empty lines
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

Alternatively, file_get_contents() can retrieve the file content as a single string.

Backendarrayfile handlingfile function
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.