【问题标题】:PHP open a php file and replace contentPHP打开一个php文件并替换内容
【发布时间】:2018-08-05 20:00:25
【问题描述】:

我想打开一个php文件并替换内容我试过这段代码但是没有用,

$fh = fopen("c/".$file."/underbaba.php", 'w');
$file = file_get_contents($fh);
$file = str_replace('error":4,', 'error":0,', $file);

这个系统打开我的文件并删除文件underbaba.php中的所有代码,我需要一个代码,因为我有很多文件要编辑我使用scandirforeach读取所有目录中的文件c名字underbaba.php,谢谢。

【问题讨论】:

标签: php fopen str-replace


【解决方案1】:

您的问题:

如果您使用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 );

与使用fopenfreadfseekfwritefclose 的序列相比,您的开销很小,因为文件打开和关闭两次,但我不认为这是问题。

值得一提的是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

【讨论】:

  • 那么要么文件路径错误,要么你没有读写文件的权限。你得到一个错误还是什么?
【解决方案2】:

您需要在append mode 使用a+r+ 模式下打开文件

请查看以下链接以获取帮助 https://www.w3schools.com/php/php_file_open.asp

【讨论】:

    【解决方案3】:

    如果这就是你所做的一切,那么是的,你正在清空你的文件。根据manual

    'w' 只为写入而打开;将文件指针放在开头 文件并将文件截断为零长度。如果文件没有 不存在,尝试创建它。

    你是否也将修改后的字符串写回文件中的某个地方?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-01
      • 2011-04-04
      • 1970-01-01
      • 2017-04-13
      • 2017-08-10
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多