file_get_contents() and file()

string file_get_contents ( string filename [, bool use_include_path [, resource context]])

array file ( string filename [, bool use_include_path [, resource context]])

The next evolutionary step up from readfile() is just called file_get_contents(), and also takes one parameter for the filename to open. This time, however, it does not output any data - instead, it will return the contents of the file as string, replete with new line characters \n where appropriate

Here is file_get_contents() in use:

<?php
    $filestring
= file_get_contents($filename);
    print
$filestring;
?>

$Filename, as mentioned already, is a variable used to represent a file you have chosen already, whether that be on Unix or Windows, which means that file_get_contents() opens that file and places its contents into $filestring. Effectively that piece of code is the same as our call to readfile(), but only because we're not doing anything with $filestring once we have it.

Consider this script:

<?php
    $filestring
= file_get_contents($filename);
    
$filearray = explode("\n", $filestring);

    while (list(
$var, $val) = each($filearray)) {
        ++
$var;
        
$val = trim($val);
        print
"Line $var: $val<br />";
    }
?>

This time we use explode() to turn $filestring into an array, which is then iterated through, outputting one line at a time with line numbers. Remember that array indices start at 0, so we need ++$var to make sure that it starts at line 1 rather than line 0. Also, note that we call trim() on $val - this is because each element in the array still has its new line character \n at the end, and trim() will take that off.

File_get_contents() is an excellent general-purpose file-handling function that you will likely find yourself using extensively.

As an alternative, if you find yourself always wanting your files inside arrays, you can use the file() function - it works in the same manner as file_get_contents(), with the exception that it returns an array, which each line in the file returned as an element.

 

Next chapter: fopen() and fread() >>

Previous chapter: readfile()

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar