PHP文件读写

时间:2011-07-24 04:43:53

标签: php

我可以从/读取同一个文件吗?如果是的话,你能解释一下吗? 该怎么做

4 个答案:

答案 0 :(得分:6)

Yes it is.

$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!

答案 1 :(得分:0)

在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
?>

答案 2 :(得分:-1)

file_put_contents("write.txt",file_get_contents("read.txt"));

答案 3 :(得分:-2)