【问题标题】:How do I loop over this xml structure and create an array from it in PHP我如何循环这个 xml 结构并在 PHP 中从它创建一个数组
【发布时间】:2017-03-17 16:50:07
【问题描述】:

我有一个 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 arrays xml foreach


    【解决方案1】:

    这应该没问题:

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

    【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2012-04-26
    • 2010-11-22
    相关资源
    最近更新 更多