Page 1 of 1

Reading, Writing, and Appending Files Like they taught in school, two Rs and an A Rate Topic: -----

#1 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 26 May 2008 - 12:38 AM

While programming PHP applications, you may one day find yourself overcome with the desire to read, write, and edit text files. This tutorial is to help you achieve that life long dream. Here we'll cover the very basics of file editing, including the fwrite(), fread(), and fgets() functions.

First, the entire script:

<?php

// Function 1
function openFile($filename, $mode) {

  $fp = fopen($filename, $mode) or die ( mysql_error() );
  
  return $fp;

}

// Function 2
function writeFile() {

  $file = openFile("test.txt", "w");

  $text = "This has been written to the file";

  fwrite($file, $text);

  fclose($file);  

}

// Function 3
function appendFile() {

  $file = openFile("test.txt", "a");

  $text = "\nThis has been appended to the file";

  fwrite($file, $text);

  fclose($file);

}

// Function 4
function readTheFile() {

  $file = fopen("test.txt", "r");

  $filecontents = fread( $file, filesize("test.txt") );

  echo $filecontents . "<br /><br />";
  
  fclose($file);

}

// Function 5
function readFiveCharacters() {

  $file = fopen("test.txt", "r");
  
  $line = fread( $file, 5);
  
  echo $line . "<br /><br />";
  
  fclose($file);

}

// Function 6
function readLine() {

  $file = fopen("test.txt", "r");
	while ($line = fgets($file)) {
		echo $line . "<br />";
	}
  
  fclose($file);

}

writeFile();
appendFile();
readTheFile();
readFiveCharacters();
readLine();

?>




Function 1 - openFile():

This is a small function I wrote that attempts to open a file. If the file opening fails, the script halts on the die() function. If you are opening a file for writing, and the file does not exist, one is created for you. If a file is opened for reading but it doesn't exist, you will receive an error and the program will quit.

Function 2 - writeFile():

First we attempt to open the file, which won't be a problem because we're opening it with mode 'w'. When using the fopen() function to open a file, you pass two parameters. Your first parameter is the name of the file you are attempting to open. The second parameter is the mode in which you would like to open the file. The three we will be learning about are 'w', 'a', and 'r' which are write, append, and read, respectively. We could also use 'x' to force a fail if the file does not exist, despite the mode.

Opening the file in 'w' mode will place the file pointer at the beginning of the file. If the file previously existed, it will be overwritten. All data that was previously in the file will be deleted.

So we open the file for writing, and create a variable, $line, which holds the line of text we wish to write. We then call the fwrite() function with the file as the first parameter, and the text to be written in the second parameter. Finally, we call the fclose() function to close the file. This is very important to keep memory on the server free.

Function 3 - appendFile():

Again, we attempt to open the file. This time we're passing mode 'a'. This is what we use to append the text to the end of the file. If you wish to add data to the end of the file and keep from overwriting the previous data, this is the mode you want to use.

So again we set a $line variable and write it to the file. This time, the line is added to the end of the file. You can open the file and take a look, and you'll see that the text is written on the next line.

But wait! Take a look at that '\n' newline character. That adds a line break in the file. If you hadn't put that in, the file would just contain

This has been written to the fileThis has been appended to the file

Notice how it's all written on the same line? Remember your line breaks!

Function 4 - readTheFile():

First, it would have made more sense to name this function readFile() to keep in theme with the rest of the functions, but readfile() is a reserved function that comes with PHP. Hence readTheFile().

Anyway, again we open the file. Next, we call the fread() function. The first parameter is our file that we opened. The second parameter is the number of bytes you wish to read from the file. By calling filesize("test.txt"), we are asking to read the entire size of the file, which is the entire file.

Echoing out the file will display the entire file on one line. Remember, HTML does not process line breaks.

Function 5 - readFiveCharacters():

This function is almost the same as the above one, with a small difference. Rather than reading the entire file, we only read the first 5 bytes. One character is equivalent to one byte, so we are in effecting reading the first 5 characters. Echoing out the result will prove so. In this case, you will see 'This ' . Note that the space is counted as one character.

Function 6 - readLine():

Lets say you want to process the text file line by line. In this case you would want to use the fgets() function. fgets() will read the next line in the file every time it is called. In this function we want to read every line and print them to the browser.

Every time we call $line = fgets($file), fgets() puts the next line into the variable $line. We run the whole thing in a while loop which pulls each line from the file and prints it out, followed by a line break.

Conclusion:

That should be what you need to get started on file writing. Now you can go write a log analyzer, flat file database, or other crazy file editing program. As always, comments, suggestions, and corrections are available. If you want more information about each function, be sure to read the PHP Manual on php.net.

Is This A Good Question/Topic? 0
  • +

Replies To: Reading, Writing, and Appending Files

#2 jcarrott  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-July 08

Posted 23 July 2008 - 09:04 AM

View Postakozlik, on 26 May, 2008 - 12:38 AM, said:

While programming PHP applications, you may one day find yourself overcome with the desire to read, write, and edit text files. This tutorial is to help you achieve that life long dream. Here we'll cover the very basics of file editing, including the fwrite(), fread(), and fgets() functions.

First, the entire script:

<?php

// Function 1
function openFile($filename, $mode) {

  $fp = fopen($filename, $mode) or die ( mysql_error() );
  
  return $fp;

}

// Function 2
function writeFile() {

  $file = openFile("test.txt", "w");

  $text = "This has been written to the file";

  fwrite($file, $text);

  fclose($file);  

}

// Function 3
function appendFile() {

  $file = openFile("test.txt", "a");

  $text = "\nThis has been appended to the file";

  fwrite($file, $text);

  fclose($file);

}

// Function 4
function readTheFile() {

  $file = fopen("test.txt", "r");

  $filecontents = fread( $file, filesize("test.txt") );

  echo $filecontents . "<br /><br />";
  
  fclose($file);

}

// Function 5
function readFiveCharacters() {

  $file = fopen("test.txt", "r");
  
  $line = fread( $file, 5);
  
  echo $line . "<br /><br />";
  
  fclose($file);

}

// Function 6
function readLine() {

  $file = fopen("test.txt", "r");
	while ($line = fgets($file)) {
		echo $line . "<br />";
	}
  
  fclose($file);

}

writeFile();
appendFile();
readTheFile();
readFiveCharacters();
readLine();

?>




Function 1 - openFile():

This is a small function I wrote that attempts to open a file. If the file opening fails, the script halts on the die() function. If you are opening a file for writing, and the file does not exist, one is created for you. If a file is opened for reading but it doesn't exist, you will receive an error and the program will quit.

Function 2 - writeFile():

First we attempt to open the file, which won't be a problem because we're opening it with mode 'w'. When using the fopen() function to open a file, you pass two parameters. Your first parameter is the name of the file you are attempting to open. The second parameter is the mode in which you would like to open the file. The three we will be learning about are 'w', 'a', and 'r' which are write, append, and read, respectively. We could also use 'x' to force a fail if the file does not exist, despite the mode.

Opening the file in 'w' mode will place the file pointer at the beginning of the file. If the file previously existed, it will be overwritten. All data that was previously in the file will be deleted.

So we open the file for writing, and create a variable, $line, which holds the line of text we wish to write. We then call the fwrite() function with the file as the first parameter, and the text to be written in the second parameter. Finally, we call the fclose() function to close the file. This is very important to keep memory on the server free.

Function 3 - appendFile():

Again, we attempt to open the file. This time we're passing mode 'a'. This is what we use to append the text to the end of the file. If you wish to add data to the end of the file and keep from overwriting the previous data, this is the mode you want to use.

So again we set a $line variable and write it to the file. This time, the line is added to the end of the file. You can open the file and take a look, and you'll see that the text is written on the next line.

But wait! Take a look at that '\n' newline character. That adds a line break in the file. If you hadn't put that in, the file would just contain

This has been written to the fileThis has been appended to the file

Notice how it's all written on the same line? Remember your line breaks!

Function 4 - readTheFile():

First, it would have made more sense to name this function readFile() to keep in theme with the rest of the functions, but readfile() is a reserved function that comes with PHP. Hence readTheFile().

Anyway, again we open the file. Next, we call the fread() function. The first parameter is our file that we opened. The second parameter is the number of bytes you wish to read from the file. By calling filesize("test.txt"), we are asking to read the entire size of the file, which is the entire file.

Echoing out the file will display the entire file on one line. Remember, HTML does not process line breaks.

Function 5 - readFiveCharacters():

This function is almost the same as the above one, with a small difference. Rather than reading the entire file, we only read the first 5 bytes. One character is equivalent to one byte, so we are in effecting reading the first 5 characters. Echoing out the result will prove so. In this case, you will see 'This ' . Note that the space is counted as one character.

Function 6 - readLine():

Lets say you want to process the text file line by line. In this case you would want to use the fgets() function. fgets() will read the next line in the file every time it is called. In this function we want to read every line and print them to the browser.

Every time we call $line = fgets($file), fgets() puts the next line into the variable $line. We run the whole thing in a while loop which pulls each line from the file and prints it out, followed by a line break.

Conclusion:

That should be what you need to get started on file writing. Now you can go write a log analyzer, flat file database, or other crazy file editing program. As always, comments, suggestions, and corrections are available. If you want more information about each function, be sure to read the PHP Manual on php.net.

Was This Post Helpful? 0
  • +
  • -

#3 jcarrott  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 23-July 08

Posted 23 July 2008 - 09:12 AM

I am working in a .htm file, so I added this code after the Javascript code.

<script langauge=php>

function saveFile(strHtml) {
name = '/lawson/xhrnet/EmailStubs/' + authUser.employee + '_PayStub_' + CheckNum + '.html';
$file = openFile(name, "w");
$text = "This has been written to the file";
fwrite($file, $text);
fclose($file);
}

function openFile($filename, $mode) {
$fp = fopen($filename, $mode);
return $fp;
}


</script>

I received an error with your origianl code, that is why I removed the or die ( mysql_error() ). My code did not have a function mysql_error() and I did not know what you did in it.

I am now getting an 'object expected' error running the function openFile(). The file that is being opened does not exist, so it needs to be created.

Is the creation code in your mysql_error() code?
Was This Post Helpful? 0
  • +
  • -

#4 jam_altun_23  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 18-July 08

Posted 24 July 2008 - 12:54 PM

Thanks for this tutorial.
I like it. It is simple and understandable for me and I think everyone...
Was This Post Helpful? 0
  • +
  • -

#5 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 24 July 2008 - 12:56 PM

View Postjam_altun_23, on 24 Jul, 2008 - 03:54 PM, said:

Thanks for this tutorial.
I like it. It is simple and understandable for me and I think everyone...


Cool, glad you like it. I have a bunch of others around the PHP Tutorial section so check 'em out.
Was This Post Helpful? 0
  • +
  • -

#6 mahendra_22patil  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 17
  • Joined: 15-August 08

Posted 18 August 2008 - 12:54 AM

View Postakozlik, on 24 Jul, 2008 - 12:56 PM, said:

View Postjam_altun_23, on 24 Jul, 2008 - 03:54 PM, said:

Thanks for this tutorial.
I like it. It is simple and understandable for me and I think everyone...


Cool, glad you like it. I have a bunch of others around the PHP Tutorial section so check 'em out.



hi friend
how to delete content of text file using PHP :rolleyes: ???????
Was This Post Helpful? 0
  • +
  • -

#7 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 89
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 18 August 2008 - 12:31 PM

Quote

hi friend
how to delete content of text file using PHP :rolleyes: ???????


Post the question in the PHP forum and I'll check it out. It'll also get more publicity there, so your chances of getting a quick answer are better. When you post make sure you describe precisely what you're trying to do. Deleting context of a text file is pretty broad. Thanks.
Was This Post Helpful? 0
  • +
  • -

#8 cult  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 23
  • Joined: 04-August 09

Posted 04 August 2009 - 08:39 AM

Hi!
I am also new in programing,so little help please.I try to find on net something to help,but I couldn't find.
I put in text file some information with form(text fields),then I need read back this information with alphabet order.
Example line(name of book,author,genre):I need sort name of the book with alphabet order.
Please little help.
Thanks
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1