Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to read a file

Short answer

file_get_contents() returns the content as one string:

<?php
 
$file = sys_get_temp_dir() . '/recipe-read.txt';
file_put_contents($file, "first\nsecond\n");
 
echo file_get_contents($file);

Output:

first
second

An array of lines

file() with the FILE_IGNORE_NEW_LINES flag returns the lines without line breaks:

<?php
 
$file = sys_get_temp_dir() . '/recipe-read.txt';
file_put_contents($file, "first\nsecond\n");
 
echo implode(' | ', file($file, FILE_IGNORE_NEW_LINES));

Output:

first | second

A large file

Read one line at a time so the whole file is never in memory:

<?php
 
$file = sys_get_temp_dir() . '/recipe-read.txt';
file_put_contents($file, "first\nsecond\n");
 
$handle = fopen($file, 'r');
$count = 0;
 
while (fgets($handle) !== false) {
    $count++;
}
 
fclose($handle);
 
echo $count;

Output:

2

Functions used in this recipe

  • file_get_contents — Reads a whole file into a string.
  • file — Reads a file into an array of lines.
  • fopen — Opens a file for reading or writing piece by piece.

Thanks for reading!

Donate to the site — we work hard for you.