遍历PHP中的XML结构

时间:2014-10-14 13:18:41

标签: php simplexml

如何读取数组的此对象中的状态

当我

时,我得到了这个结果
$xml   = simplexml_load_string($xml_string);

display_output($xml->country[0]);

结果:

SimpleXMLElement::__set_state(array(
   '@attributes' => 
   array (
    'name' => 'Afghanistan',
),
'state' => 
array (
0 => 'Badakhshan',
1 => 'Badghis',
2 => 'Baghlan',
3 => 'Balkh',
4 => 'Bamian',
5 => 'Farah',
6 => 'Faryab',
7 => 'Ghazni',
8 => 'Ghowr',
9 => 'Helmand',
10 => 'Herat',
11 => 'Jowzjan',
12 => 'Kabol',
13 => 'Kandahar',
14 => 'Kapisa',
15 => 'Konar',
16 => 'Kondoz',
17 => 'Laghman',
18 => 'Lowgar',
19 => 'Nangarhar',
20 => 'Nimruz',
21 => 'Oruzgan',
22 => 'Paktia',
23 => 'Paktika',
24 => 'Parvan',
25 => 'Samangan',
26 => 'Sar-e Pol',
27 => 'Takhar',
28 => 'Vardak',
29 => 'Zabol',
),
))

我想得到这个州,我怎么能这样做?我试过了,不幸的是它没有用。

$a = $xml->country[0]->state[0];

*下面是xml:

<?xml version="1.0" encoding="utf-8"?>
<countries>
 <country name="Afghanistan">
    <state>Badakhshan</state>
    <state>Badghis</state>
    <state>Baghlan</state>
    <state>Balkh</state>
    <state>Zabol</state>
  </country>
</countries>

更新,找到了答案

            $xml   = simplexml_load_string($xml_string);

            $country = array();
            $state = array();

            for($x=0;$x<count($xml);$x++)
            {
                $country[] = (string)$xml->country[$x]->attributes()->name;
                if(isset($xml->country[$x]->state))
                {
                    for($y=0;$y<count($xml->country[$x]->state);$y++)
                    {
                        $state[$x][] = (string)$xml->country[$x]->state[$y];
                    }
                }
            }

            return array($country,$state);

1 个答案:

答案 0 :(得分:1)

我认为你会使用xpath在country元素上查找属性“Afghanistan”,因为你知道这是你想要获取数据的国家。

$afghanistan = $xml->xpath("//country[@name='Afghanistan']");
$afghan_states = $afghanistan->state;
$first_state = $afghan_states[0];

或者,如果您不需要国家/地区级别信息,则可以使用更具体的xpath选择器:

$afghan_states = $xml->xpath("//country[@name='Afghanistan']/state");
$first_state = $afghan_states[0];

即使XML中的国家/地区元素排序发生了变化,这也会使您的代码正常工作。