首页 技术 正文
技术 2022年11月14日
0 收藏 370 点赞 4,828 浏览 1159 个字

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
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,028
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,518
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,365
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,146
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,780
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,857