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:

<?php
// Read a file into an array via HTTP
$lines = file('http://www.example.com/');
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />
";
}

// 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.