tags:

views:

50

answers:

3

Can anyone tell the method to modify/delete the contents of a text file using PHP

+2  A: 

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?

Metalshark
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
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
thanks a lot...the array function worked good.
ayush
+3  A: 

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

nikic
A: 

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.

Ghost