2016-11-03 85 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 –