使用PHP替换大文件中的字符

时间:2015-05-11 10:07:16

标签: php replace large-files file-handling

我尝试使用此代码替换大型XML文件(110MB)中的单引号但发生错误。我需要一个可以处理至少3GB XML文件的代码。

错误讯息:

  

致命错误:允许的内存大小为134217728字节   (尝试分配20449728个字节)在C:\ xampp \ htdocs \ replace.php上   第10行

<?php
    replace_file('electronics.xml', "'", "&#39;");

    function replace_file($path, $string, $replace)
    {
        $file = fopen($path, 'a+');
        while (feof($file) === false)
        {
            $str=file_get_contents($path);
            $str=str_replace($string, $replace, fgets($file));
        }
        fclose($file);
}
echo "replace done";
?>

3 个答案:

答案 0 :(得分:1)

不建议将大文件读入php。调用适当的命令行,例如sed

参考:http://www.grymoire.com/Unix/Sed.html

答案 1 :(得分:0)

简化:

$str = str_replace( "'","&#39;",file_get_contents('electronics.xml'));

这是非常错误的:

打开XML

    $file = fopen($path, 'a+');

While循环无理由,fgets读取到文件末尾,因此循环在第一次迭代时完成。

    while (feof($file) === false)  
    {

再次读取同一文件的全部内容,无用

        $str=file_get_contents($path);  

读取整个文件,未指定长度,因此读取到EOF

        $str=str_replace($string, $replace, fgets($file));  
    }
    fclose($file); 

没有任何成就。

答案 2 :(得分:0)

next()
相关问题