[ Team LiB ] Previous Section Next Section

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 all the elements of the array to form a single string:


$file_array = file( "test.txt" );
$contents = implode( $file_array );


    [ Team LiB ] Previous Section Next Section