用PHP解析大型嵌套XML表单的最佳方法是什么?
我试图用PHP解析一个相当大的XML表,但我对它很陌生。 XML表单包含几千条记录。用PHP解析大型嵌套XML表单的最佳方法是什么?
这里是片内使用的结构的例子:
<familyList>
<family>
<familyID>1234</familyID>
<familyDescription>The Jonathans</familyDescription>
<childrenList>
<child>Suzan</child>
<child>Fred</child>
<child>Harry</child>
</childrenList>
</family>
<family>
<familyID>1235</familyID>
<familyDescription>The Gregories</familyDescription>
<childrenList>
<child>Anthony</child>
<child>Lindsay</child>
</childrenList>
</family>
</familyList>
当我是相当新的XML的解析使用PHP,我不知道这将是解析这个嵌套XML的最好的办法工作表放入数组中。我需要将XML转换为数组,以便随后将数据插入到MySQL数据库中。
能否请你给我推在正确的方向,因为我还没有成功的令人费解了解决办法SOFAR?..
谢谢!
DOMDocument有很多优秀的访问,更新和输出格式化XML的方法。关于转换为数组,我建议在的数组中使用对象,这是PHP完全适用的,我发现语法比用于跟踪这种层次结构的数组更清晰。
<?php
// load xml families, could split this into different files..
$families = new DOMDocument();
$families->load("/xml/families.xml"); // your xml file
$families_items = $families->getElementsByTagName("family");
$my_cool_array = null; // reset this variable for being set as an array literal later
foreach($families_items as $family_item) {
$toinsert = null; // reset the object literal
$toinsert->family_id = $family_item->getElementsByTagName('familyID')->nodeValue;
$toinsert->familyDescription= $family_item->getElementsByTagName('familyDescription')->nodeValue;
$children = $family_item->getElementsByTagName('childrenList')->childNodes;
// children
foreach ($children as $child) {
$child_toinsert[]->name = $child->nodeValue;
}
// etc for your details, syntax might be a bit off, but should get you started
$toinsert->children = $child_toinsert;
// build array of objects
$my_cool_array_of_families[] = $toinsert;
}
var_dump($my_cool_array);
这样的事情,仔细检查语法,但它是在路上;)
DOM很棒,但DOM会将整个XML文件加载到内存中,这在OP的情况下可能是不可行的,因为他有很大的文件。 – Gordon 2010-08-02 13:28:08
当您解析大型XML文件时,应该使用XML Pull Parser(XPP)来执行此操作。 PHP有一个pull解析器的实现,它被称为XMLReader。将XML存储为大文件的数组也会消耗大量内存。
我推荐你使用XMLReader,当你解析数据时,你可以将它插入到数据库中而不用等待文件结束。它不会占用大量的内存,而且速度会更快。
This tutorial可以很好地了解如何在PHP中使用XMLReader。
已经指出,如果评论3210可以成为解析大型XML文件的其他解决方案。
是如何的问题([大数据量的XML解析] http://stackoverflow.com/不同问题/ 3387371/xml-parsing-of-large-of-data)**一小时前**已被问到? – Gordon 2010-08-02 13:10:05