Read/Write 在 PHP 中没有使用太多内存的大型 XML

Read/Write large XMLs without using too much memory in PHP

我正在尝试查询一些非常大的 XML 文件(最多几个 gig),检查它们的格式是否正确,然后将它们写入硬盘。看起来很容易,但由于它们太大了,我无法在内存中存储整个文档。因此我的问题是: 当可用 RAM 小于一个文档的大小时,如何读取、检查和写入大型 XML 文件?

我的方法: 使用 XMLReader 逐个节点读取它(如果成功,文档必须格式正确)并使用 XMLWriter 进行写入。问题:XMLWriter 似乎将所有内容都存储在 RAM 中,直到文档完成。 DOM Documents 和 SimpleXML 似乎也是如此。还有什么我可以尝试的吗?

您的方法似乎很合适,要解决 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/