6 Ways to Read Files In PHP – Into String, Array, And More!

Welcome to a tutorial on how to read files in PHP. Yep, that is right, how difficult can reading files in PHP be? You will be surprised… It is not as straightforward as some may think.

There are quite a number of ways to read files in PHP:

  1. Read file into a string – $contents = file_get_contents("FILE");
  2. Read file into an array – $array = file("FILE");
  3. Use cURL to fetch a file from a different server.
    • $curl = curl_init("http://site.com/");
    • curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    • $data = curl_exec($curl);
    • curl_close($curl);
  4. Open a file stream and read line-by-line.
    • $stream = fopen("FILE", "r");
    • while($line = fgets($stream)) { echo $line; }
  5. Read and directly output – readfile("FILE");
  6. Directly load a file into the script – include "FILE"; require "FILE";

That is a quick overview of the common methods, but let us walk through some examples in this guide – Read on!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

READ FILES IN PHP

All right, let us now get into the various ways to read files in PHP.

 

TUTORIAL VIDEO

 

1) READ FILE INTO A STRING

1-file-to-string.php
<?php
// (A) READ ENTIRE CONTENTS INTO A STRING
$text = file_get_contents("README.txt");
echo $text;
 
// (B) ALSO CAN FETCH FROM URL
$text = file_get_contents("https://en.wikipedia.org/wiki/Aha_ha");
echo $text;

There is not much rocket science involved here, just take note that file_get_contents() can fetch contents from a file or URL. While this is straightforward, take extra care to not read massive files with this… You will run into an “out of memory” error, and possibly cause some issues on the server.

 

 

2) READ FILE INTO AN ARRAY

2-file-to-array.php
<?php
// (A) FILE TO ARRAY
$array = file("README.txt");
print_r($array);
 
// (B) ADDITIONAL OPTION - SKIP EMPTY LINES
$array = file("README.txt", FILE_SKIP_EMPTY_LINES);
print_r($array);

This is another simple one. But instead of a flat string, file() will read into an array instead, with each element being a different line. Take note again, do not attempt to read large files with this.

 

3) CURL FETCH

3-curl.php
<?php
$curl = curl_init("https://en.wikipedia.org/wiki/Aha_ha");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
echo $data;

CURL stands for “client URL”, and in layman’s term “server-to-server calls”. Some of you guys may be thinking – What the heck, isn’t this a roundabout way of doing file_get_contents()? Well no. CURL actually offers a lot of options and controls – It can even fetch files from an FTP server. Will leave the reference links below if you are interested.

 

 

4) READ FILE LINE-BY-LINE

4-line-by-line.php
<?php
// (A) OPEN FILE
$handle = fopen("README.txt", "r") or exit("Error reading file!");
 
// (B) READ LINE BY LINE
while ($line = fgets($handle)) {
// you can also specify how many bytes to read at once
// while (($line = fgets($handle, 4096)) !== false) {
  echo $line;
}
 
// (C) CLOSE FILE
fclose($handle);

The above 3 methods will run into a memory problem when dealing with large files. So to deal with that problem, we can use fgets() and read line-by-line instead.

 

5) FILE STREAM

5-file-stream.php
<?php
// (A) START OUTPUT BUFFER
$file = "README.txt";
ob_start();
 
// (B) HTTP HEADERS TO FORCE DOWNLOAD
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$file\"");
header("Expires: 0");
header("Cache-Control: must-revalidate");
header("Pragma: public");
header("Content-Length: ".filesize($file));
 
// (C) OUTPUT ALL THE HEADERS & STOP BUFFERING
ob_end_flush();
 
// (D) READ AND OUTPUT FILE DIRECTLY
readfile($file);
exit();

This next method is a little different from the rest. Instead of reading a file into strings and arrays, it directly outputs it. Very useful when it comes to forcing a download or transferring huge files.

 

 

6) INCLUDE OR REQUIRE

6-include-require.php
<!DOCTYPE HTML>
<html>
<body>
  <?php require "README.txt"; ?>
</body>
</html>

You have probably heard of include and require since day 1 of learning PHP – Yes, they can be used for any file type actually.

 

EXTRAS

That’s all for this guide, and here are some extras and links that may be useful.

 

THE SUMMARY

Function Description Reference
$STRING = file_get_contents(FILE OR URL); Reads file into a string. Click Here
$ARRAY = file(FILE); Reads file into an array, separated by line breaks. Click Here
$CURL = curl_init(URL); Initializes CURL. Click Here
curl_setopt($CURL, OPTION, VALUE); Set the cURL options. At the bare minimum, we have to set CURLOPT_RETURNTRANSFER to retrieve data. Click Here
$DATA = curl_exec($CURL); Execute CURL. Click Here
curl_close($CURL) Close the CURL connection. Click Here
$HANDLE = fopen(FILE, "r"); Opens a file stream. Click Here
while ($LINE = fgets($HANDLE)) { ... } Read line-by-line. Click Here
fclose($HANDLE); Close the file stream Click Here
readfile(FILE); Read and directly output file. Click Here
require FILE Load specified file/script – Throws an error and halt if the file cannot be opened. Click Here
include FILE Load specified file/script – Throws a warning but will not halt if the file cannot be opened. Click Here

 

THE END

Thank you for reading, and we have come to the end of this short guide. I hope this has helped to solve your file reading yoga issues, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “6 Ways to Read Files In PHP – Into String, Array, And More!”

  1. Saša Živković

    there is an error in example 4: Open a file stream and read line-by-line.

    $stream = fopen(“FILE”, “r”);
    while(($line=fgets($handle))!==false) { echo $line; }

    instead of $handle there should be $stream!

Leave a Comment

Your email address will not be published. Required fields are marked *