我正在尝试查询一些非常大的XML文件(最多几个演出),检查它们是否格式良好,并将它们写入硬盘。看起来很简单,但由于它们太大,我无法在内存中存储整个文档。因此我的问题是: 当RAM少于一个文档时,如何读取,检查和编写大型XML文件?
我的方法: 使用XMLReader逐节点读取它(如果成功,则文档必须格式正确)并使用XMLWriter进行编写。问题:XMLWriter似乎将所有内容存储在RAM中,直到文档完成。 DOM Documents和SimpleXML似乎也是这样。还有什么我可以尝试的吗?
答案 0 :(得分:1)
您的方法似乎很合适,为了解决XMLWriter的RAM问题,您可以尝试定期将内存刷新到输出文件中。
<?php
$xmlWriter = new XMLWriter();
$xmlWriter->openMemory();
$xmlWriter->startDocument('1.0', 'UTF-8');
for ($i=0; $i<=10000000; ++$i) {
$xmlWriter->startElement('message');
$xmlWriter->writeElement('content', 'Example content');
$xmlWriter->endElement();
// Flush XML in memory to file every 1000 iterations
if (0 == $i%1000) {
file_put_contents('example.xml', $xmlWriter->flush(true), FILE_APPEND);
}
}
// Final flush to make sure we haven't missed anything
file_put_contents('example.xml', $xmlWriter->flush(true), FILE_APPEND);`
来源:http://codeinthehole.com/tips/creating-large-xml-files-with-php/