Can anyone tell the method to modify/delete the contents of a text file using PHP
-
possible duplicate of [Clearing content of text file using php](http://stackoverflow.com/questions/1073609/clearing-content-of-text-file-using-php) – Gordon Jul 12 '10 at 18:36
-
1*(tutorial)* [Practical PHP - Chapter 8: Files](http://www.tuxradar.com/practicalphp/8/0/0) – Gordon Jul 12 '10 at 18:38
3 Answers
Using file_put_contents
:
file_put_contents($filename, 'file_content');
If you want to append to the file instead of replacing it's contents use:
file_put_contents($filename, 'append_this', FILE_APPEND);
(file_out_contents
is the simpler alternative to using the whole fopen
complex.)

- 100,734
- 37
- 191
- 225
By using fopen:
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
}
Write "" to a file to delete its contents.
To delete contents line by line use:
$arr = file($fileName);
unset($arr[3]); // 3 is an arbitrary line
then write the file contents. Or are you referring to memory mapped files?

- 8,194
- 7
- 34
- 49
-
You can use stream seeking http://uk3.php.net/manual/en/streamwrapper.stream-seek.php and writing http://uk3.php.net/manual/en/streamwrapper.stream-write.php if your use fopen. – Metalshark Jul 12 '10 at 18:45
-
This tutorial may offer you what you are after (for binary files - so lower level file editing) http://en.kioskea.net/faq/998-parsing-a-binary-file-in-php – Metalshark Jul 12 '10 at 18:48
There are number of ways to read files. Large files can be handled very fast using
$fd = fopen ("log.txt", "r"); // you can use w/a switches to write append text
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
you can also use file_get_contents() to read files. its short way of achieving same thing.
to modify or append file you can use
$filePointer = fopen("log.txt", "a");
fputs($filePointer, "Text HERE TO WRITE");
fclose($filePointer);
YOU CAN ALSO LOAD THE FILE INTO ARRAY AND THEN PERFORM SEARCH OPERATION TO DELETE THE SPECIFIC ELEMENTS OF THE ARRAY.
$lines = file('FILE WITH COMPLETE PATH.')
; // SINGLE SLASH SHOULD BE DOUBLE SLASH IN THE PATH SOMTHING LIKE C://PATH//TO//FILE.TXT
Above code will load the file in $lines array.

- 25,073
- 20
- 81
- 128