Dja*_*son 5 php xml large-files large-data xml-parsing
我正在尝试并需要一些帮助,执行以下操作:
我想流式解析PHP的大型XML文件(4 GB).我不能使用简单的XML或DOM,因为它们将整个文件加载到内存中,所以我需要一些可以传输文件的东西.
我怎么能用PHP做到这一点?
我想要做的是浏览一系列<doc>元素.并将他们的一些孩子写入一个新的xml文件.
我试图解析的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>
Run Code Online (Sandbox Code Playgroud)
我正在尝试将每个<doc>元素的所有子元素复制到一个新的XML文件中,除了<links>元素及其子元素.
所以我希望新的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>
Run Code Online (Sandbox Code Playgroud)
我非常感谢在流/流解析/流读取原始XML文件,然后将其一些内容写入PHP中的新XML文件中的任何和所有帮助.
这是一个大学尝试。这假设正在使用一个文件,并且您想要写入一个文件:
<?php
$interestingNodes = array('title','url','abstract');
$xmlObject = new XMLReader();
$xmlObject->open('bigolfile.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();
?>
Run Code Online (Sandbox Code Playgroud)