Reading the Contents of a File with file_get_contents()

The file reading functions we have covered so far give you a lot of control. If your objective is to read the contents of a file into a variable, however, there is a nice blunt tool to get the job done. The file_get_contents() function requires a string representing the path to a file and returns the file’s contents:

$contents = file_get_contents( "test.txt" );

file_get_contents() was introduced with PHP 4.3. If you are using an older version of PHP, you can use the file() function to achieve a similar effect. file() requires a file path and returns an array, and each element of the returned array contains a line of the file’s contents. You can then use the implode() function to join ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.