我正在尝试流式解析大约 4GB 的 XML 文件并将其部分写入 PHP 中的新 XML 文件。
~4GB XML 文档的结构是这样的,我试图保留<doc>
元素及其<title></title>
<url></url>
子元素<abstract></abstract>
。
但是当我运行这个脚本时,我得到的只是一个<doc />
每行一个文件。所以基本上它是复制<doc>
元素并使它们自动关闭,而不是复制它的子元素。
<?php
$interestingNodes = array('title','url','abstract');
$xmlObject = new XMLReader();
$xmlObject->open('file.xml');
$xmlOutput = new XMLWriter();
$xmlOutput->openURI('destfile.xml');
$xmlOutput->setIndent(true);
$xmlOutput->setIndentString(" ");
$xmlOutput->startDocument('1.0', 'UTF-8');
while($xmlObject->read()){
if($xmlObject->name == 'doc'){
$xmlOutput->startElement('doc');
$xmlObject->readInnerXML();
if(array_search($xmlObject->name, $interestingNodes)){
$xmlOutput->startElement($xmlObject->name);
$xmlOutput->text($xmlObject->value);
$xmlOutput->endElement(); //close the current node
}
$xmlOutput->endElement(); //close the doc node
}
}
$xmlObject->close();
$xmlOutput->endDocument();
$xmlOutput->flush();
?>
这是 file.xml 的样子:
<feed>
<doc>
<title>Title of first doc is here</title>
<url>URL is here</url>
<abstract>Abstract is here...</abstract>
<links>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
</link>
</doc>
<doc>
<title>Title of second doc is here</title>
<url>URL is here</url>
<abstract>Abstract is here...</abstract>
<links>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
<sublink>Link is here</sublink>
</link>
</doc>
</feed>
这就是我希望 destfile.xml 的样子:
<doc>
<title>Title of first doc is here</title>
<url>URL is here</url>
<abstract>Abstract is here...</abstract>
</doc>
<doc>
<title>Title of second doc is here</title>
<url>URL is here</url>
<abstract>Abstract is here...</abstract>
</doc>
但是,当我在上面运行该脚本时,我得到的只是:
<doc />
<doc />
<doc />
<doc />
<doc />
<doc />
/* And many, many more <doc />s */