Php在抓取巨大文件时内存限制问题


Php memory limit issue while scraping huge file

我正在用Simple Html-Dom抓取这个巨大的xml文件(300k行~11MB),并遇到一些内存限制问题。因此,我添加了一些php.ini命令来覆盖默认设置并启用对内存的完全控制。坏主意。

我的代码:

include('simple_html_dom.php');
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '-1');
$xml = file_get_contents('HugeFile.xml'); 
$xml2 = new simple_html_dom();
$xml2->load($xml);
foreach($xml2->find('tag1') as $element) {
        $element->innertext = str_replace('text to replace','new text',$element>innertext);
    }
$html->save('output'.xml');    
}

现在,有没有一种方法可以让这个脚本在合理的时间内顺利运行,而不会出现任何内存问题?这可以用文本编辑器轻松完成,但我需要自动化,因为我有很多文件要编辑。

找到了一个更好的方法:这里不需要DOM,我只在file_get_contents返回的字符串中填充str_replace,然后用file_put_contents将其放在另一个文件中。简单整洁:

$xml = file_get_contents('HugeFile.xml'); 
$new = str_replace('text to replace','new text',$xml);
file_put_contents('output.xml');    

对于复杂的修改,preg_replace可能会派上用场。