How to read an entire file to a string using PHP?
To read a file line by line, you use the
fgets()
function:fgets ( resource $handle , int $length = ? ) : string|false
The following example uses the
fread()
function to read the contents of the entire population.txt file into a string and shows it on the webpage:<?php
$filename = './public/population.txt';
$f = fopen($filename, 'r');
if ($f) {
$contents = fread($f, filesize($filename));
fclose($f);
echo nl2br($contents);
}