2010-08-02 64 views
0

我試圖用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?..

謝謝!

+3

是如何的問題([大數據量的XML解析] http://stackoverflow.com/不同問題/ 3387371/xml-parsing-of-large-of-data)**一小時前**已被問到? – Gordon 2010-08-02 13:10:05

回答

0

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); 

這樣的事情,仔細檢查語法,但它是在路上;)

+2

DOM很棒,但DOM會將整個XML文件加載到內存中,這在OP的情況下可能是不可行的,因爲他有很大的文件。 – Gordon 2010-08-02 13:28:08

5

當您解析大型XML文件時,應該使用XML Pull Parser(XPP)來執行此操作。 PHP有一個pull解析器的實現,它被稱爲XMLReader。將XML存儲爲大文件的數組也會消耗大量內存。

我推薦你使用XMLReader,當你解析數據時,你可以將它插入到數據庫中而不用等待文件結束。它不會佔用大量的內存,而且速度會更快。

This tutorial可以很好地瞭解如何在PHP中使用XMLReader。

已經指出,如果評論​​3210可以成爲解析大型XML文件的其他解決方案。

+0

我在ircmaxell的現在刪除的答案下面看到了您的評論。據我所知[Xml Parser](http://us2.php.net/manual/en/book.xml.php)是一個基於事件的解析器,因此非常適合大文件。 – Gordon 2010-08-02 13:35:09

+0

@戈登,對不起,我把它與SimpleXML和DOMDocument混淆,它們都加載了整個文檔。我將添加Xml解析器有一個其他可能的解決方案。 – HoLyVieR 2010-08-02 13:55:50

相關問題