Is it possible for me to read from / and write to the same file? If so, could you explain me how to do that
$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!
In PHP 5 file_put_contents
is the easiest way:
<?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"));
Here is some documentation. You can see there all the parameters you can use in these functions.
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.