Skip to main content

PHP text file handling (Read and Write)



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:


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

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);
?>

to read through whole file:

$fp = fopen("filetest.txt","r");

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


filesizefilesize 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!";

?>

Comments

Popular posts from this blog

Laravel XAMPP MySQL artisan migrate install error mysql.sock

In my previous post I wrote about setting up Laravel 4 on Mac with XAMPP . When I tried to use migrations (using artisan) I faced some issue. I will also post about Laravel migrations soon.    php artisan migrate:install Error :                                                     [PDOException]                                       SQLSTATE[HY000] [2002] No such file or directory                                              Solution : We need to tell artisan which mysql we want it to use. For this to work we need to porivde it with mysql.sock which we want it to use. So change your database settings like this: 'mysql' => array( 'driver'    => 'mysql', 'host'      => 'localhost',     'unix_socket' => '/Applications/xampp/xamppfiles/var/mysql/mysql.sock', 'database'  => 'wedding', 'username'  => 'root', 'password'  => '', '

Add (Drop) a new article (table) at publisher in merge replication

Let us add the article using the GUI first. First of all create the table on publisher database. Now right click on the publisher and select properties from the menu. Click on articles. Uncheck the - "Show only checked articles in the list" checkbox, in order to see the newly added table. Select the table as shown in the figure below. Press ok The article has now been added to the publisher We now need to recreate the snapshot Right click the publication and select – “View snapshot agent status”. Click start to regenerate snapshot. Now right click on the subscription (I have both on same server you may have on different servers) and select “View synchronization status” Click on start on the agent. The schema changes will propagate to the client if you have "Replicate schema changes" property set to true in the publisher.

Check SQL Server Job status (State) using sp_help_job and xp_sqlagent_enum_jobs

This article is about checking the status of a SQL job. In our work place we have lot of SQL jobs. These jobs will run whole day and are business critical. They will load the data and generate extracts which will be used by business people. Thus, it becomes quite essential to support the system efficiently so that the job finishes in time and as desired. Also, while designing a new system sometimes we need to check the dependency of one job over another. In such scenario we need to check whether a particular job has finished or not. All this can be achieved in SQL Server by using the procedures:- sp_help_job xp_sqlagent_enum_jobs Note: xp_sqlagent_enum_jobs is an undocumented proc inside of sp_help_job and is used extensively to get SQL agent job information. sp_help_job: This procedure gives some insight into the status, and information, about a job. This stored procedure provides information such as last start time, job status etc. Syntax sp_help_job { [ @job_id= ] jo