PHP File Open / Read
Three common ways to read a file. Pick by size — and by whether you need it all at once or one line at a time.
Everything as one string
PHP
$text = file_get_contents('hello.txt');
echo $text;
Good for config files, small data. Loads the whole file into memory.
Line-by-line as an array
PHP
$lines = file('hello.txt'); // each line keeps its newline
$lines = file('hello.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $i => $line) {
echo $i, ': ', $line, PHP_EOL;
}
Streaming with fopen
The right way for big files — memory stays flat:
PHP
$fh = fopen('big.log', 'r');
while (($line = fgets($fh)) !== false) {
process(rtrim($line));
}
fclose($fh);
Read a chunk
PHP
$fh = fopen('big.bin', 'rb');
$chunk = fread($fh, 4096); // first 4 KB
fseek($fh, 1024); // move to byte 1024
$rest = fread($fh, 1024); // next 1 KB
fclose($fh);
CSV
PHP
$fh = fopen('users.csv', 'r');
$headers = fgetcsv($fh);
while (($row = fgetcsv($fh)) !== false) {
$user = array_combine($headers, $row);
echo $user['name'], ' ', $user['email'], PHP_EOL;
}
fclose($fh);
JSON
PHP
$config = json_decode(file_get_contents('config.json'), true);
print_r($config);
Tip:
file_get_contents() works on URLs too if allow_url_fopen is on. For real HTTP work use curl or a library like Guzzle — better error handling, timeouts, retries.Example
Example
<?php
$fh = fopen('hello.txt', 'r');
while (!feof($fh)) {
echo fgets($fh);
}
fclose($fh);
Try it Yourself »
Exercise
Read CSV rows one at a time.
while (($row =
($fh)) !== false) {}
Seven letters; starts with f.
Discussion
Loading…