dongzhuonao8429 2015-04-02 21:44
浏览 49
已采纳

在PHP中读取XML字符串[重复]

This question already has an answer here:

I am struggling to read this XML string when applying simplexml_load_string

The XML is as below:-

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

With var_dump(simplexml_load_string($xml)); I get the following:-

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"
   }
  }
 }
}

I am trying to read the contents within the <fc:Location band........ for example the "21:39" arrival time. However the var_dump(simplexml_load_string($xml)); does not show this part of the XML as an array as you can see above. It seems to miss off everything between <fc:Location................ and </fc:Location>

I was hoping that using the code below I could read the "21:39" arrival time.

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

All I get is a syntax error ........for the ":".

</div>
  • 写回答

1条回答 默认 最新

  • dporu02280 2015-04-02 21:59
    关注

    You'd get those attributes by traversing properly and using the attributes() method.

    $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 />';
    }
    

    Note that namespaces can be accessed by using the children() method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组