[英]Get attribute from xml file php
<?xml version="1.0" encoding="UTF-8"?>
<abc-response>
<error-messages>
<errors code="302">
User does not have access to this Product
</errors>
</error-messages>
</abc-response>
am using simplexml_load_string and using the attribute function to get the code and I keep getting a null value. 我正在使用simplexml_load_string并使用属性函数来获取代码,并且我一直得到一个空值。
$results = simplexml_load_string($response);
$errorCode = $results->attributes()->{'errors'};
You need to navigate to the element with the attribute you want. 您需要导航到具有所需属性的元素。 There are lots of ways.
有很多方法。
echo $results->{'error-messages'}->errors['code'];//302
This works just fine since there's just one error-messages
and one errors
. 这很好用,因为只有一个
error-messages
和一个errors
。 If you had several, you could use array notation to indicate the one you want. 如果你有几个,你可以使用数组表示法来表示你想要的那个。 So the line below also echoes
302
所以下面的行也与
302
相呼应
echo $results->{'error-messages'}[0]->errors[0]['code'];
You could even use xpath
, a query language to traverse xml. 你甚至可以使用
xpath
,一种查询语言来遍历xml。 The //
will return all nodes by name: //
将按名称返回所有节点:
echo $results->xpath('//errors')[0]->attributes()->code; //302
echo
shows a number, but it's still an object. echo
显示一个数字,但它仍然是一个对象。 If you'd like to capture just the integer, cast it like this: 如果您只想捕获整数,请将其转换为:
$errorCode = (int) $results->{'error-messages'}->errors['code'];
Check out this really helpful intro . 看看这个非常有用的介绍 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.