简体   繁体   中英

File Handling using PHP

谁能告诉方法使用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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM