Help - Search - Members - Calendar
Full Version: Delete from Text File using PHP
Invision Power Services > Community Forums > Community Web Design and Coding
Why Two Kay
I know of methods to create and append to text files using PHP, but is there way to delete specific portions? This is used for keeping a simple list (without using a database). Each "item" is a single string with no spaces, and each item is on it's own line. Any ideas?
Brendon Koz
Use filegetcontents() to read the file into a string.

Use explode() to get the contents of the file/string into an array (since they're just single items, right?).

Loop through the array to remove what you wanted to remove.

Output the array (using implode()) back to the file.



This is just one way. You can get much more advanced ways of doing things, such as using the Berkeley DB (flatfile) abstraction methods.
Zainzz
QUOTE(malikyte @ Mar 14 2006, 06:04 AM) *
Use filegetcontents() to read the file into a string.

Use explode() to get the contents of the file/string into an array (since they're just single items, right?).


i THINK simple file function can do that? http://www.php.net/file .. Correct me if i'm wrong please

CODE
<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
   echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
?>
Brendon Koz
file() will in fact put things into an array, however the KEY is the line number. If that's a desired effect, and you NEED the line number, then by all means use that. However, filegetcontents() is supposedly the most efficient way to get file contents into a string. So, for speed and efficiency, it just depends on how well explode() works, I suppose.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.