Writing the File at Once: file_put_contents


Writing the File at Once: file_put_contents

Here's a shortcut if you want to write some text to a fileuse the file_put_contents function. This function writes a string to a file, and here's how you use it in general:

 file_put_contents (string filename, string data [, int flags [, resource context]]) 

Here, filename is the name of the file you want to write, data is the string text to write, flags can be FILE_USE_INCLUDE_PATH, FILE_APPEND, or both, and context is a file context (which is beyond the scope of this book). The function returns the number of bytes that were written to the file.

This function is very much the same as calling fopen, fwrite, and fclose automaticallyyou don't have to open or close the file yourself, and you don't need a file handle. Here's an example, phpfileputcontents.php, Example 7-13. All you have to do is decide on the text you want to store:

 $text = "Here\nis\nthe\ntext.";         .         .         . 

Then you can use file_put_contents to store the text in a file you give by name, not by handle:

 $text = "Here\nis\nthe\ntext."; if (file_put_contents("text.txt", $text) == FALSE) {     echo "Cannot write to text.txt."; }         .         .         . 

If a problem occurs, you can report it, as shown in phpfileputcontents.php, Example 7-13.

Example 7-13. Using file_put_contents to write text to a file, phpfileputcontents.php
 <HTML>     <HEAD>         <TITLE>             Appending to a file with file_put_contents         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Appending to a file with file_put_contents             </H1>             <?php                 $text = "Here\nis\nthe\ntext.";                 if (file_put_contents("text.txt", $text) == FALSE) {                     echo "Cannot write to text.txt.";                 }                 else {                     echo "Wrote to the file text.txt.";                 }             ?>         </CENTER>     </BODY> </HTML> 

You can see the results in Figure 7-13, where the application is telling us that it was successful.

Figure 7-13. Writing a file using file_put_contents.


Here's what was written to the file:

 Here is the text. 

Not bad. That completes our discussion in this chapter of OOP and file handling. In the next chapter, we're going to dig deeper into storing and working with data on the server by handling databases for a big lift in programming power.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net