約 4GB の XML ファイルをストリーム解析し、その一部を PHP の新しい XML ファイルに書き込もうとしています。
~4GB の XML ドキュメントの構造はこのようなもので、要素とその子を保持しようとしています。<doc>
<title></title>
<url></url>
<abstract></abstract>
しかし、このスクリプトを実行すると、各行に<doc />
1 つのファイルが表示されるだけです。したがって、基本的には、<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 */