我有一个xml节点,它的结构是这样的:
<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),
)
这应该没问题:
<?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);
?>