2009-06-16 30 views
6

我想寫一個函數來解析(理論上)未知的XML數據結構到等價的PHP數組中。用PHP(DOM)迭代未知的XML結構

這裏是我的示例XML:

<?xml version="1.0" encoding="UTF-8"?> 
<content> 

<title>Sample Text</title> 

<introduction> 
    <paragraph>This is some rudimentary text</paragraph> 
</introduction> 
<description> 
    <paragraph>Here is some more text</paragraph> 
    <paragraph>Even MORE text</paragraph> 
    <sub_section> 
     <sub_para>This is a smaller, sub paragraph</sub_para> 
     <sub_para>This is another smaller, sub paragraph</sub_para> 
    </sub_section> 
</description> 
</content> 

我修改從devarticles這個DOM遍歷功能:

$data = 'path/to/xmldoc.xml'; 
$xmlDoc = new DOMDocument(); #create a DOM element 
$xmlDoc->load($data); #load data into the element 
$xmlRoot = $xmlDoc->firstChild; #establish root 

function xml2array($node) 
    { 
    if ($node->hasChildNodes()) 
    { 
$subNodes = $node->childNodes; 
    foreach ($subNodes as $subNode) 
     { 
     #filter node types 
     if (($subNode->nodeType != 3) || (($subNode->nodeType == 3))) 
      { 
      $arraydata[$subNode->nodeName]=$subNode->nodeValue; 
      } 
     xml2array($subNode); 
     } 
     } 
     return $arraydata; 
    } 
//The getNodesInfo function call 

$xmlarray = xml2array($xmlRoot); 


// print the output - with a little bit of formatting for ease of use... 
foreach($xmlarray as $xkey) 
    { 
    echo"$xkey<br/><br/>"; 
    } 

現在,因爲這樣我傳遞的元素添加到陣列I」 m覆蓋共享一個節點名稱的任何元素(因爲我理想的是要給這些密鑰命名與它們的始發節點相同的名稱)。我的遞歸併不是很好......但是,即使我清空括號 - 第二層節點依然在的第一層(請參閱說明節點的文本)。

任何人都有任何想法,我可以更好地構造這個?

回答

2

你可能會更好只是抽絲一些代碼斷網

http://www.bin-co.com/php/scripts/xml2array/

/** 
    * xml2array() will convert the given XML text to an array in the XML structure. 
    * Link: http://www.bin-co.com/php/scripts/xml2array/ 
    * Arguments : $contents - The XML text 
    *    $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value. 
    *    $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance. 
    * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure. 
    * Examples: $array = xml2array(file_get_contents('feed.xml')); 
    *    $array = xml2array(file_get_contents('feed.xml', 1, 'attribute')); 
    */ 
    function xml2array($contents, $get_attributes=1, $priority = 'tag') { 
1

您可能會感興趣的SimpleXMLxml_parse_into_struct

$ arraydata既不傳遞給後續調用xml2array(),也不是所使用的返回值,所以是「我的遞歸併不大......」是真的;-)
追加到一個新元素現有的數組可以使用空方括號,$ arr [] = 123; $ arr [$ x] [] = 123;

+0

我沒有做,早在經過陣列的方法,但我想弄清楚它爲什麼沒有看到這些二線節點。另外,如何繼續在未知深度的數組上添加最後一組空圓括號? – sunwukung 2009-06-16 23:43:22

+0

我的意思是,你看過你的帖子中的劇本......這是一個野獸! – sunwukung 2009-06-16 23:45:41