This article is about Text File Handling in PHP. Though now a days we generally use database and XML files for storage but there are still some scenarios in which we need file handling. Well, here are a couple of reasons why you might need to work with files:
- To move binary data (such as image files) into a database as BLOBs (Binary Large Objects)
- To import data (such as email addresses) that has been exported from a legacy database or application.
- To export data out of a database into a text file so that it can be processed offline
Rest I am sure you will think of yourself :)!!!
File functions in PHP are very similar to those found in the C++ fstream library. Like C++ we first open the file in Read/Write mode and then will actually Read/Write it.
Opening a text file
We open a file using fopen function. fopen stands for "file open", and is used to create a pointer to the file which we want to open for read/write access. It accepts 2 required and 2 optional parameters. Its signature is shown below:
int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])
For example, let's say that we wanted to open a file called filetest.txt. We would use fopen like this:
int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])
For example, let's say that we wanted to open a file called filetest.txt. We would use fopen like this:
$fp = fopen("filetest.txt", "r");
...
?>
The $fp variable would now contain a pointer (or reference) to the filetest.txt file. The second parameter, "r", tells PHP that we want to open the file in read mode only.
There are 8 different file modes that we can use when working with files in PHP. They are shown below (courtesy of php.net):
- 'r' - Open for reading only; place the file pointer at the beginning of the file.
- 'r+' - Open for reading and writing; place the file pointer at the beginning of the 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.
- 'x' - Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
- 'x+' - Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
Reading a Text File
We use below mentioned functions in general to read a file:
feof, fread, fgets, fgetc, filesize, file_exists, fclose
feof – Here “f” just tells that it is a file handling function and “eof” stands for “end of file”. It is used in PHP to determine whether or not we have reached the end of a file.
Here is the syntax for it:
int feof ( int fp)
The parameter, fp, is a reference to a file pointer that contains the details of the file we're working with. Feof returns true if we're at the end of a file, and false if we're not.
The parameter, fp, is a reference to a file pointer that contains the details of the file we're working with. Feof returns true if we're at the end of a file, and false if we're not.
fread - The fread() reads from an open file. The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the read string, or FALSE on failure.
Here is the syntax for it:
fread(file, length)
$fp = fopen("filetest.txt","r");
$content = fread($fp,filesize("filetest.txt"));
echo $content;
fclose($fp);
?>
or to break the lines when new line is encountered
$fp = fopen("filetest.txt","r");
global $content,$fileSize;
$content = fread($fp,filesize("filetest.txt"));
$value = explode("\r\n", $content);
echo "Content: </br>";
echo $value[0];
echo "</br>";
echo $value[1];
fclose($fp);
?>
fgets - The fgets() function returns a line from an open file. The fgets() function stops returning on a new line, at the specified length, or at EOF, whichever comes first. This function returns FALSE on failure.
Here is the syntax for it:
fgets(file,[optional]length)
$fp = fopen("filetest.txt","r");
echo fgets($fp);
fclose($fp);
?>
echo fgets($fp);
fclose($fp);
?>
to read through whole file:
$fp = fopen("filetest.txt","r");
while(! feof($fp))
{
echo fgets($fp). "</br>";
}
fclose($fp);
while(! feof($fp))
{
echo fgets($fp). "</br>";
}
fclose($fp);
?>
fgetc- The fgetc() function returns a single character from an open file.
Here is the syntax for it:
fgetc(file)
$fp = fopen("filetest.txt","r");
echo fgetc($fp);
fclose($fp);
?>
to read whole file:
$fp = fopen("filetest.txt","r");
while(!feof($fp))
{
$char = fgetc($fp);
if($char == "\n")
{
echo "</br>";
}
echo $char;
}
fclose($fp);
?>
Note: This function is slow and should not be used on large files. If you need to read one character at a time from a large file, use fgets() to read data one line at a time and then process the line one character at a time with fgetc().
filesize – filesize is a PHP function which accepts a file name. It returns the length of that file in bytes.
Here is the syntax for it:
filesize(filename)
file_exists – file_exists is PHP function which accepts a file name and checks for the presence of that file. It returns true if the file is present else false.
Here is the syntax for it:
file_exists(filename)
fclose - The fclose() function closes an open file. This function returns TRUE on success or FALSE on failure.
Writing a Text File
For writing the file we will use fwrite function of PHP. The fwrite() writes to an open file. The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the number of bytes written, or FALSE on failure.
This means that we need to open the file first and then should write on it. This is the reason that we have different filemode.
Here is the syntax for fwrite function:
fwrite(file,string,[optional]length)
file - Specifies the open file to write to
string – Specifies the string to write to the open file.
length - Specifies the maximum number of bytes to write to the file.
$fp = fopen("test.txt","w");
echo fwrite($fp,"Write Something!!!");
fclose($fp);
?>
The output of the above code will be 18 (number bytes written).
In order to create a blank text file we can just write:
$fp = fopen("test1.txt","w");
fclose($fp);
?>
Note: Using filemode as “w” will truncate the file.
Thus in order to append to the file we need to use filemode “a”.
So, to append a sentence to the bottom of test.txt, we could use this code:
$fp = fopen("test.txt", "a")
$bytes = fwrite($fp, "\r\nLook, it's a brand new line!");
fclose($fp);
echo "Wrote $bytes bytes to the end of test.txt!";
?>
$fp = fopen("test.txt", "a")
$bytes = fwrite($fp, "\r\nLook, it's a brand new line!");
fclose($fp);
echo "Wrote $bytes bytes to the end of test.txt!";
?>
Comments
Post a Comment