2016-11-03 60 views
1

數組我有構造這樣一個XML節點:我如何遍歷這個XML結構,並從它創建的PHP

<ItemDimensions> 
    <Height Units="hundredths-inches">42</Height> 
    <Length Units="hundredths-inches">752</Length> 
    <Weight Units="hundredths-pounds">69</Weight> 
    <Width Units="hundredths-inches">453</Width> 
</ItemDimensions> 

我如何遍歷這個XML,並得到屬性,單位和值到一個數組?

例如我想建立一個數組,看起來像這樣:

$itemDimensions = array(
    array('height','hundredths-inches',24), 
    array('length,','hundredths-inches',752), 
    array('weight','hundredths-pounds',69), 
    array('width','hundredths-inches',453), 
    ) 

回答

0

這應該是確定:

<?php 

$x = '<ItemDimensions> 
     <Height Units="hundredths-inches">42</Height> 
     <Length Units="hundredths-inches">752</Length> 
     <Weight Units="hundredths-pounds">69</Weight> 
     <Width Units="hundredths-inches">453</Width> 
     </ItemDimensions>'; 

$xml = new DOMDocument(); 
$xml->loadXML($x); 
$dimensions = $xml->getElementsByTagName('ItemDimensions'); 

$array = array(); 

$i = 0; 
while(is_object($node = $dimensions->item($i))){ 
    foreach($node->childNodes as $n){ 
     if($n->nodeType === XML_ELEMENT_NODE) { 
      $array[] = array($n->nodeName,$n->getAttribute('Units'),$n->nodeValue); 
     }   
    } 
    $i++; 
} 
var_dump($array); 
?> 
+0

這是一些可重複使用的代碼。 https://phpro.org/examples/XML-To-Array-With-PHP.html –