关于数组:在PHP中读取XML字符串

Reading XML String In PHP

本问题已经有最佳答案,请猛点这里访问。

应用simplexml_load_string

时,我很难读取此XML字符串

XML如下:-

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>                  
 <Pport xmlns:fc="http://www.thalesgroup.com/rtti/PushPort/Forecasts/v2" xmlns:ct="http://www.thalesgroup.com/rtti/PushPort/CommonTypes/v1" ts="2015-04-02T21:40:43.6505299+01:00" version="12.0" xmlns="http://www.thalesgroup.com/rtti/PushPort/v12">
    <uR updateOrigin="TD">          
        <TS rid="201504021071622" uid="L24370" ssd="2015-04-02">        
            <fc:Location tpl="SHRDHST" wta="21:39:30" wtd="21:40" pta="21:40" ptd="21:40">  
                <fc:arr at="21:39" src="TD" />
                <fc:dep at="21:40" src="TD" />
                <fc:plat>2</fc:plat>
            </fc:Location>  
        </TS>      
    </uR>          
 </Pport>

使用var_dump(simplexml_load_string($xml));,我得到以下信息:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
object(SimpleXMLElement)#3 (2) {
["@attributes"]=>
 array(2) {
  ["ts"]=>
  string(33)"2015-04-02T21:40:43.6505299+01:00"
  ["version"]=>
  string(4)"12.0"
}
["uR"]=>
object(SimpleXMLElement)#4 (2) {
["@attributes"]=>
 array(1) {
  ["updateOrigin"]=>
  string(2)"TD"
}
["TS"]=>
object(SimpleXMLElement)#5 (1) {
 ["@attributes"]=>
  array(3) {
    ["rid"]=>
    string(15)"201504021071622"
    ["uid"]=>
    string(6)"L24370"
    ["ssd"]=>
    string(10)"2015-04-02"
   }
  }
 }
}

我正在尝试读取<fc:Location band........中的内容,例如" 21:39 "到达时间。但是,var_dump(simplexml_load_string($xml));并未将XML的这一部分显示为数组,如您在上面看到的那样。似乎错过了<fc:Location................</fc:Location>

之间的所有内容

我希望使用下面的代码可以读取" 21:39 "到达时间。

1
2
3
4
5
$newxml = simplexml_load_string($xml);
foreach ($newxml->TS->fc:Location->fc:arr->movedata as $movedata) {
   $uid=$movedata['at'];
   echo $uid;
}

我所得到的只是" : "的语法错误.........


您可以通过正确遍历并使用attributes()方法来获得这些属性。

1
2
3
4
5
6
7
8
$newxml = simplexml_load_string($xml);
$children = $newxml->uR->TS->children('fc', true)->children('fc', true);

foreach($children as $movedata) {
    $attr = $movedata[0]->attributes();
    $uid = $attr['at'];
    echo $uid . '<br />';
}

请注意,可以使用children()方法访问名称空间。