Open file, replace string save in different Directory
Looking for a simple way to open a source php file, replace some predefined tags, then save the fi开发者_运维知识库le in a different directory. I am looking for a way to do it without copying the file to a tmp dir, replacing tags, then copying the file again.
Is there a way to do this in one quick pass?
Well, just use file_get_contents()
and file_put_contents()
like below and you'll not need any temp files:
<?php
//open file and get data
$data = file_get_contents("path/to/sourcefile.php");
// do tag replacements or whatever you want
$data = str_replace("<tag1>", "<tag2>", $data);
//save it back:
file_put_contents("path/to/destinationfile.php", $data);
?>
Why not copy it to a new file, and then do your replacement in the copied file? Why would you need a temporary file?
精彩评论