有没有更好的方法来遍历此XML列表

时间:2011-07-04 02:04:33

标签: php xml loops simplexml

这是循环

 function List($input) 
{   //I'm sure there's a better way of doing this... 
    $list =  simplexml_load_string($input);
    foreach($list->nation as $nation){
        foreach($nation->region as $region){
            $temp['url']=  (string)$region['url']; 
            $temp['name'] = (string)$region['name']; 
            $temp['nation'] = (string)$nation['name'];
            $out['regions'][] = $temp;              
        }
        $temp['url'] = (string)$nation['url'];
        $temp['name'] = (string)$nation['name'];
        unset($temp['nation']);  
        $out['nations'][] = $temp;
    }
    return $out;        
}

示例数据:

<?xml version="1.0"?>
<regions>
  <nation url="canada" name="Canada" >
    <region url="abbotsford" name="Abbotsford" />
    <region url="barrie" name="Barrie" />
    <region url="brantford" name="Brantford" />
    <region url="calgary" name="Calgary" />
    <region url="charlottetown" name="Charlottetown" />
 </nation>
 <nation url="ireland" name="Ireland">
    <region url="cork" name="Cork"/>
    <region url="dublin" name="Dublin"/>
    <region url="galway" name="Galway"/>
    <region url="limerick" name="Limerick"/>
    <region url="waterford" name="Waterford"/>
 </nation>

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

function List($input) {
    $list = simplexml_load_string($input);

    // guarantee fixed output format
    $out = array('regions' => array(), 'nations' => array());

    foreach ($list->nation as $nation){
        foreach ($nation->region as $region){
            $out['regions'][] = array(
                'url'    => $region['url'],
                'name'   => $region['name'],
                'nation' => $nation['name']
            );
        }

        $out['nations'][] = array(
            'url'  => $nation['url'],
            'name' => $nation['name']
        );
    }

    return $out;        
}