PHP
  Home arrow PHP arrow Page 3 - Working With Text Files in PHP
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Working With Text Files in PHP
By: Mitchell Harper
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 78
    2002-12-18

    Table of Contents:
  • Working With Text Files in PHP
  • Opening and Reading Files
  • Creating and Writing Files
  • File Writing in Action
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Working With Text Files in PHP - Creating and Writing Files


    (Page 3 of 5 )

    Files are flexible. They can contain text or binary data. They can contain anything from a single character to 100,000 lines of XML. It is this flexibility combined with PHP's simply file-handling functions that make files such an easy-to-use aspect of PHP.

    On the last page we learnt how to open and read files. Creating and writing files is very similar –- we start with the fopen function:

    Here are all of the file modes that relate to writing to a file:
    • 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
    • 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
    • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
    • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
    So by simply specifying "w" as the file mode, PHP will move the file pointer to the beginning of the file and truncate (cut-down) the file to zero length if that file already exists. If it doesn't exist, here's the good part -- PHP will automatically create it for us!

    So, how would we create a blank file using just the fopen command? Simple. Take a look:

    <?php

    $fp = fopen("newfile.file", "w") or die("Couldn't create new file");

    ?>


    That's really all there is to it. To actually output a value to the file, we need to use the fwrite function, which we will discuss now.

    fwrite
    Fwrite simply writes the contents of a string to a file. The signature for the fwrite function looks like this:

    int fwrite ( int fp, string string [, int length])

    Fwrite returns the number of bytes written on success, or false if an error occurs. The first parameter is the file pointer ($fp in all of our previous examples). The second parameter is the string that you want to write to the file, and the third optional parameter is the length of the string that will be output to the file.

    If we wanted to output a simple sentence to a file, then we could do it like this:

    <?php

    $fp = fopen("newfile.file", "w") or die("Couldn't create new file");
    $numBytes = fwrite($fp, "Hello, this is some text!");
    fclose($fp);

    echo "Wrote $numBytes bytes to newfile.file!";

    ?>


    Newfile.file now looks like this:

    The contents of newfile.file

    The output from our PHP script shows how many bytes were written to newfile.file:

    The number of bytes written to newfile.file

    Simple, right! Now, remember that using the file mode "w" actually truncates the file before writing to it. What about if we just wanted to append some text to the bottom of the file? Which file mode would we use then? We have 2 choices:
    • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
    • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
    Because we are only performing write operations on the file, we will use "a" (remember that it's quicker to use a unidirectional access method instead of a bi-directional one, such as read/write).

    So, to append a sentence to the bottom of newfile.file, we could use this code:

    <?php

    $fp = fopen("newfile.file", "a") or die("Couldn't create new file");
    $numBytes = fwrite($fp, "\r\nLook, it's a brand new line!");
    fclose($fp);

    echo "Wrote $numBytes bytes to the end of newfile.file!";

    ?>


    Newfile.file now looks like this:

    Adding a new line to newfile.file 

    Before we continue, try experimenting with the different file modes to see how they work.

    More PHP Articles
    More By Mitchell Harper


     

    PHP ARTICLES

    - Making Usage Statistics in PHP
    - Installing PHP under Windows: Further Config...
    - File Version Management in PHP
    - Statistical View of Data in a Clustered Bar ...
    - Creating a Multi-File Upload Script in PHP
    - Executing Microsoft SQL Server Stored Proced...
    - Code 10x More Efficiently Using Data Access ...
    - A Few Tips for Speeding Up PHP Code
    - The Modular Web Page
    - Quick E-Commerce with PHP and PayPal
    - Regression Testing With JMeter
    - Building an Iterator with PHP
    - PHP Frontend to ImageMagick
    - Using PEAR's mimeDecode Module
    - Incoming Mail and PHP






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT