943,910 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Unsolved
  • Views: 5620
  • PHP RSS
Dec 24th, 2007
0

Deleting a line from a file

Expand Post »
Hi,

I'm trying to fully automate my website, and I'm trying to delete a line from a file that matches the line in a given String.
For example, I have a txt file named toApprove.txt containing a list of names such as:
PHP Syntax (Toggle Plain Text)
  1. John
  2. Joe
  3. George
  4. Jake
The file is kept in that format. So, if I have a variable holding "Joe", how do I remove the line that says "Joe" from the text file and keep the rest. here's what I tried ($_GET["file"] represents the line I want to remove):
PHP Syntax (Toggle Plain Text)
  1. $file=fopen("toApprove.txt","r+");
  2. $file2=fopen("temp.txt","w+");
  3. while(!feof($file))
  4. {
  5. $str = fgets($file);
  6. if($str != $_GET["file"])
  7. {
  8. fwrite($file2,$str);
  9. }
  10. }
  11. fclose($file);
  12. fclose($file2);
  13.  
  14. $file=fopen("toApprove.txt","w+");
  15. $file2=fopen("temp.txt","r");
  16. while(!feof($file2))
  17. {
  18. $str = fgets($file2);
  19. fwrite($file,$str);
  20. }
  21. fclose($file);
  22. fclose($file2);

Thanks so much for your help!
Last edited by Ghost; Dec 24th, 2007 at 7:05 am.
Similar Threads
Reputation Points: 12
Solved Threads: 2
Posting Whiz
Ghost is offline Offline
352 posts
since Aug 2004
Dec 25th, 2007
1

Re: Deleting a line from a file

Is there an error you're getting? I don't see any particular problem in the code.

Normally, you'd want to have a database do this job for you. It is much simpler than having to read/write from files.

For example, with a DB it is as simple as:

PHP Syntax (Toggle Plain Text)
  1. $result = $Db->Query("DELETE FROM `table` WHERE `column` = '".mysql_real_escape_string($_GET["file"])
  2. ."' LIMIT 1";

The database then does basically what you are doing with the files, on the disk or memory depending on the storage type being used. Databases are very efficient at this though by design.

Your code is very good for file updates as it is very memory efficient. If you are working with small files, you could save time by doing something like:

PHP Syntax (Toggle Plain Text)
  1. // retrieve file into a string
  2. $txt = file_get_contents('toApprove.txt');
  3. // replace the line with $_GET["file"], assuming line break is \n
  4. $txt = str_replace(trim($_GET["file"])."\n", '', $txt);
  5. // write the string back to the file
  6. file_put_contents('toApprove.txt', $txt);

or

PHP Syntax (Toggle Plain Text)
  1. // retrieve the file into an array where each line is a value
  2. $Array = file('toApprove.txt');
  3. // assuming unique values, lets remove the Array key with value $_GET["file"]
  4. unset($Array[array_search(trim($_GET["file"]), $Array)]);
  5. // explode the array into string with line breaks seperation and put everthing back in the file
  6. file_put_contents('toApprove.txt', implode("\n", $Array));

It is much simpler, however, is memory intensive if you have a large file since you will be saving the whole file contents to a variable, $txt (PHP memory).
file_get_contents() should be more efficient than using fopen() and fgets() for smaller files.. it certainly is more convenient.

file_put_contents() is only supported on PHP5, so you can test for it and your system and create the function if it doesn't exist:

PHP Syntax (Toggle Plain Text)
  1. if (!file_exists('file_put_contents')) {
  2. // create a simple user function to emulate PHP5's file_put_contents()
  3. function file_put_contents($file, $contents) {
  4. fwrite($fp = fopen($file), $contents, strlen($contents));
  5. fclose($fp);
  6. }
  7. }

that should work for basic use.
Last edited by digital-ether; Dec 25th, 2007 at 3:50 am. Reason: code formatting
Moderator
Reputation Points: 457
Solved Threads: 101
Nearly a Posting Virtuoso
digital-ether is offline Offline
1,250 posts
since Sep 2005
Dec 25th, 2007
0

Re: Deleting a line from a file

Thanks for your help! There is no database for me to use (I'm using a free web host).
Also, I'm not getting any error message. Instead, it is just not deleting anything from the file. I will try the file_put_contents function, though. Thanks!
Reputation Points: 12
Solved Threads: 2
Posting Whiz
Ghost is offline Offline
352 posts
since Aug 2004
Dec 25th, 2007
0

Re: Deleting a line from a file

Click to Expand / Collapse  Quote originally posted by Ghost ...
Thanks for your help! There is no database for me to use (I'm using a free web host).
Also, I'm not getting any error message. Instead, it is just not deleting anything from the file. I will try the file_put_contents function, though. Thanks!
Yeah, it's usually easier to just put everything from the file in a string or array, and use the string and array functions to manipulate it. It also allows you to dump the whole string after manipulation just to see if it worked.

You may also be interested in a flat file DB. It reads and writes to disk but has similar functionality as a database. Theres a great one posted here a few weeks ago as part of a new CMS. http://www.daniweb.com/forums/post482294.html
Moderator
Reputation Points: 457
Solved Threads: 101
Nearly a Posting Virtuoso
digital-ether is offline Offline
1,250 posts
since Sep 2005
Oct 6th, 2010
0
Re: Deleting a line from a file
hi

i know this is an old post but i have a question about it.

when using this code the problem i have is that it leaves an empty line in the file where you deleted the line is there any way to do it so it doesnt put an empty line in place of your deleted line?

Nook6
Reputation Points: 10
Solved Threads: 0
Newbie Poster
nook6 is offline Offline
2 posts
since Oct 2010
Oct 7th, 2010
0
Re: Deleting a line from a file
Which code are you using?

Line breaks are represented by "\n" for unix and "\r\n" for windows.

Note that "\n" is only a single character, it is escaped with an \ to show that it is actually a meta character ie: the new line.

If you delete that "\n" together with the line you are deleting there should be no empty line left over.
Moderator
Reputation Points: 457
Solved Threads: 101
Nearly a Posting Virtuoso
digital-ether is offline Offline
1,250 posts
since Sep 2005
Oct 8th, 2010
0
Re: Deleting a line from a file
yes thankyou solved the problem i did take out the \n but then it was adding the next line to the end of the line before.

in the end i used this code:

PHP Syntax (Toggle Plain Text)
  1. // retrieve file into a string
  2. $txt = file_get_contents('database.txt');
  3. // replace the line with $_GET["file"], assuming line break is \n
  4. $txt = str_replace(trim($_GET["info"]),'', $txt);
  5. // strip out any empty lines
  6. $txt = preg_replace('/^\n+|^[\t\s]*\n+/m','',$txt);
  7. // write the string back to the file
  8. file_put_contents('database.txt', $txt);

thanks very much.

nook6
Reputation Points: 10
Solved Threads: 0
Newbie Poster
nook6 is offline Offline
2 posts
since Oct 2010
Oct 8th, 2010
0
Re: Deleting a line from a file
There is a fatal flaw to loading the entire file into an array like that. It loads the entire file into memory. If the file only has 30 lines no big deal. If the file as 30000 lines then it will be an issue.

Here is what I recommend instead (PHP 5.1.2 > only):
PHP Syntax (Toggle Plain Text)
  1. <?php
  2.  
  3. /*
  4.  * Create a new SplFileObject representation of the file
  5.  * Open it for reading and writing and place the pointer at the beginning of the file
  6.  * @see fopen for additional modes
  7.  */
  8. $file = new SplFileObject('database.txt', 'a+');
  9.  
  10. /*
  11.  * Set a bitmask of the flags to apply - Only relates to reading from file
  12.  * In this case SplFileObject::DROP_NEW_LINE to remove new line charachters
  13.  * and SplFileObject::SKIP_EMPTY to remove empty lines
  14.  */
  15. $file->setFlags(7);
  16.  
  17. /*
  18.  * Lock the file so no other user can interfere with reading and writing while we work with it
  19.  */
  20. $file->flock(LOCK_EX);
  21.  
  22. /*
  23.  * Create a SplTempFileObject
  24.  * 0 indicates not to use memory to store the temp file.
  25.  * This is probably slower than using memory, but for a large file it will be much more effective
  26.  * than loading the entire file into memory
  27.  * @see http://www.php.net/manual/en/spltempfileobject.construct.php for more details
  28.  */
  29. $temp = new SplTempFileObject(0);
  30.  
  31. /*
  32.  * Lock the temp file just in case
  33.  */
  34. $temp->flock(LOCK_EX);
  35.  
  36. /*
  37.  * The line we're hoping to match and remove
  38.  * DO NOT include any line ending charachters these have been stripped already
  39.  */
  40. $delete = 'Some line to match and delete.';
  41.  
  42. /*
  43.  * Iterate over each line of the file only loading one line into memory at any point in time
  44.  * Use trim() on the line to ensure we don't have excess whitespace anywhere
  45.  */
  46. foreach( $file as $line ){
  47.  
  48. if( trim($line) != $delete )
  49. {
  50. /*
  51. * If this line does NOT match out delete write it to the temp file
  52. * Append a line ending to it
  53. */
  54. $temp->fwrite($line.PHP_EOL);
  55. }
  56. }
  57.  
  58. /*
  59.  * Truncate the existing file to 0
  60.  */
  61. $file->ftruncate(0);
  62.  
  63.  
  64. /*
  65.  * Write the temp file back to the existing file
  66.  */
  67. foreach( $temp as $line ){
  68.  
  69. /*
  70. * Iterate over temp file and put each line back into original file
  71. */
  72. $file->fwrite($line);
  73. }
  74.  
  75. /*
  76.  * Release the file locks
  77.  */
  78. $temp->flock(LOCK_UN);
  79. $file->flock(LOCK_UN);

This way we only ever work with 1 line in memory at a time.
You could also port this code to delete a line in the file numerically by changing out the initial foreach loop to something like:

PHP Syntax (Toggle Plain Text)
  1. // Delete line 6 (Files start as 0, 1, 2, 3, etc like arrays)
  2. $delete = 5;
  3.  
  4. /*
  5.  * Iterate over each line and check its key
  6.  */
  7. foreach( $file as $key => $line ){
  8.  
  9. if( $key != $delete )
  10. {
  11. /*
  12. * If this line does NOT match out delete write it to the temp file
  13. * Append a line ending to it
  14. */
  15. $temp->fwrite($line.PHP_EOL);
  16. }
  17. }
Sponsor
Reputation Points: 265
Solved Threads: 126
Practically a Master Poster
mschroeder is offline Offline
624 posts
since Jul 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: Select the radio button and send value into table
Next Thread in PHP Forum Timeline: PHP search mssql





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC