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

最新文章

  1. wamp集成环境开启rewrite伪静态支持
  2. Java 消息摘要 散列 MD5 SHA
  3. 第9章 硬件抽象层:HAL
  4. SQL中 将同一个表中的A列更新到B列,B列更新到A列
  5. 【bzoj3674】 可持久化并查集加强版
  6. JS 中document.URL 和 window.location.href 的区别
  7. ARM Cortex-M instructions
  8. MySQL &#183; 特性分析 &#183; 内部临时表
  9. PHP常用魔术方法(__set、__get魔术方法:)
  10. CentOS 恢复 rm -rf * 误删数据(转)
  11. Foreach &amp; add remove elements
  12. @EnableAsync annotation metadata was not injected
  13. SpriteBuilder中节点的%位置移动
  14. fork子进程
  15. VS 附加到进程 加载“附加进程”弹窗很慢
  16. vmware您无权输入许可证密钥,请请使用系统管理员账户重试
  17. Spring Boot Application
  18. CentOS 安全优化
  19. HRBUST - 1818 石子合并 区间dp入门
  20. DES的加密与解密算法(Python实现)

热门文章

  1. java(POI):基于模版的Excel导出功能,局部列写保护总结
  2. 安装Ecshop首页出现报错:Only variables should be passed by referen
  3. WP8__从windowsphone app store 中根据app id获取应用的相关信息(下载网址及图片id等)
  4. Linux之通配符与转义字符
  5. 兰勃特投影C#实现
  6. SQL 常用方法
  7. Easyui扩展或者重载(方法和属性)
  8. [原]My first Python
  9. 2014年第五届蓝桥杯试题C/C++程序设计B组——李白打酒
  10. C# .Net三层架构[转]