繁体   English   中英

PHP FILES读写

[英]PHP FILES reading and writing

我可以从/读取并写入同一文件吗? 如果是这样,您能解释一下该怎么做吗

是的。

$file = "./test.txt"; 
// open file at the beginning.
$fh = fopen($file, 'r+'); 
//read the first line of the file. (advances pointer to the second line).
$contents = fread($fh); 
// modify contents.
$new_contents = str_replace("hello world", "hello", $contents); 
// make sure you're back at the 0 index.
fseek( $file, 0 );
// write
fwrite($fh, $new_contents); 
// close.
fclose($fh); 
// done!

在PHP 5中, file_put_contents是最简单的方法:

<?php
$file     = 'people.txt';
$current  = file_get_contents($file); // Open the file to get existing content
$current .= "John Smith\n";           // Append a new person to the file
file_put_contents($file, $current);   // Write the contents back to the file
?>
file_put_contents("write.txt",file_get_contents("read.txt"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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