simplexml_load_string获取xml节点里的属性值

http://stackoverflow.com/questions/14359658/get-xml-attribute-using-simplexml-load-string

问:

 

I am using a few third party APIs which returns errors via xml in the following form:

<xml>
<status>0</status> <error code="111">Error message text goes here.</error> </xml>

Using simplexml_load_string in PHP I can easily get the status 0 and the error message text but I cannot find a means of retrieving the code="111" value from the <error code="111">. It seems to get dropped by SimpleXML.

<?php
    $bytesRead = file_get_contents('http://api.....'); $xml = simplexml_load_string($bytesRead); echo '<pre>'; print_r($xml); echo '</pre>'; ?>

Outputs

SimpleXMLElement Object
( [status] => 0 [error] => Error message text goes here. )

Am I missing something? Is there a way to obtain this value or can someone suggest another method to get this?

 

回答:

 

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

Example:

$x = '<xml>
<status>0</status>
<error code="111">Error message text goes here.</error>
</xml>'; $attributeObject = simplexml_load_string($x)->error['code']; print_r($attributeObject); print_r((string) $attributeObject);

Program Output (Demo)

SimpleXMLElement Object
( [0] => 111 ) 111

转载于:https://www.cnblogs.com/walter371/p/4765530.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值