Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page