PHP: Reading a File into a String or Reading the File into an Array

Aside from the common approach in reading a file with php fopen() function which is a little annoying in that it requires extra steps before actually reading the contents of the file.

PHP has other file reading functions to enable you instantly get what you want and read the contents of the file without the need to create a file handler manually. It’s automatically taken care of in the process.

To read a file into a string

Go with file_get_contents():

$book = file_get_contents('book.txt'); // $book is a single string containing the entire contents of book.txt
To read a file into an array with each line an item

Go with file():

$book = file('book.txt'); // $book is an array with all the lines from book.txt
Scroll to Top