开发者

File Handling using PHP

Can anyone tell the method to modify/del开发者_开发问答ete the contents of a text file using PHP


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


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜