How to modify file content in PHP?

To make changes to the content of a file, you can utilize the file_get_contents() and file_put_contents() functions in PHP.

The example code is shown below:

$file = "example.txt"; // 文件路径

// 读取文件内容
$content = file_get_contents($file);

// 修改文件内容
$content = str_replace("old content", "new content", $content);

// 将修改后的内容写入文件
file_put_contents($file, $content);

In the code above, the file’s content is read using the file_get_contents() function, the content to be modified is then replaced with new content using the str_replace() function. Finally, the modified content is written back to the file using the file_put_contents() function.

Please modify the value of the $file variable and the parameters in the str_replace() function as needed to achieve your specific modifications to the file content.

bannerAds