您的问题:
如果您使用file_get_contents,您不会传递文件句柄,而是将文件路径作为字符串传递。
虽然
$fh = fopen("c/".$file."/underbaba.php", 'w');
不使用fwrite 写入文件将导致简单地擦除文件。在脚本结束之前文件应该是fclosed。
解决办法:
只需使用file_get_contents 读取文件,然后使用file_put_contents 写入。
$contents = file_get_contents( $full_path_to_file );
$contents = str_replace( 'error":4,', 'error":0,', $contents );
file_put_contents( $full_path_to_file, $contents );
与使用fopen、fread、fseek、fwrite、fclose 的序列相比,您的开销很小,因为文件打开和关闭两次,但我不认为这是问题。
值得一提的是file_get_contents 将一次读取所有整个文件并将其存储到内存中,因此该解决方案仅适用于大小合理的文件。
您可以轻松添加错误处理:
$contents = file_get_contents( $full_path_to_file );
if( $contents === false )
{
// an error occurred reading
}
$contents = str_replace( 'error":4,', 'error":0,', $contents );
$bytes_written = file_put_contents( $full_path_to_file, $contents );
if( $bytes_written !== strlen( $contents ) )
{
// an error occurred writing
}
当您对一组文件进行操作时,请在每次迭代时正确设置 for / foreach 循环设置 $full_path_to_file。
供您参考:
file_get_contents
file_put_contents