如何将XMLReader/DOMDocument与大型XML文件一起使用并防止500错误

Jef*_*sen 1 php xml xmlreader domdocument large-files

我有一个大约12mb的XML文件,大约有16000个产品.我需要将它处理成一个数据库; 然而,在大约6000行时,它会因500错误而死亡.我正在使用Kohana框架(版本3),以防万一与它有任何关系.

这是我在控制器中的代码:

$xml = new XMLReader();
$xml->open("path/to/file.xml");

$doc = new DOMDocument;

// Skip ahead to the first <product>
while ($xml->read() && $xml->name !== 'product');

// Loop through <product>'s
while ($xml->name == 'product')
{
   $node = simplexml_import_dom($doc->importNode($xml->expand(), true));
   // 2 queries to database put here
   $xml->next('product');
}
Run Code Online (Sandbox Code Playgroud)

XML是商店的一堆项目,因此两个查询是a)insert ignore商店本身和b)插入产品

任何见解将不胜感激.

小智 18

你为什么要混用XMLReader/DomDocument?只需使用XMLReader:

$reader = new XMLReader(); // initialize
$reader->open( 'file.xml' ); // open file
do {
    $sxe = simplexml_load_string( $reader->readOuterXml() ); // get current element
    echo $sxe; // echo current element
}
while( $reader->next( $this->type ) ); // repeat this for any "product" tag
Run Code Online (Sandbox Code Playgroud)

上述示例的优点是,XMLReader只会将当前标记读入内存.DomDocument读取整个文件 - 这就是你得到错误500的原因.使用给定的例子,你可以处理数百MB的XML文件,而不会增加你的内存限制(除了你尝试读取的当前标记大于可用内存).

  • +1用于为基础问题提供可扩展的解决方案。增加的内存限制无法扩展,并且在文件增长时会再次导致500。 (3认同)