Creating and Changing Files

Like reading files, creating and changing files can also be done in more than one way. There are just two options this time: file_put_contents() and fwrite(). Both of these functions complement functions we just looked at, which are file_get_contents() and fread(), respectively, and they mostly work in the same way.

file_put_contents()

This function writes to a file with the equivalent of fopen(), fwrite() (the opposite of fread()), and fclose()—all in one function, just like file_get_contents(). It takes two parameters: the filename to write to and the content to write, respectively, with a third optional parameter specifying extra flags that we will get to in a moment. If file_put_contents() is successful, it will return the number of bytes written to the file; otherwise, it will return false.

Here is an example:

    $myarray[ ] = "This is line one";
    $myarray[ ] = "This is line two";
    $myarray[ ] = "This is line three";
    $mystring = implode("\n", $myarray);
    $numbytes = file_put_contents($filename, $mystring);
    print "$numbytes bytes written\n";

That should output "52 bytes written", which is the sum total of the three lines of text plus the two new line characters used to implode() the array. Remember that the new line character is, in fact, just one character inside files, whereas PHP represents it using two: \ and n.

You can pass in a third parameter to file_put_contents() which, if set to FILE_APPEND, will append the text in your second parameter to the existing ...

Get PHP in a Nutshell 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.