<?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>我使用simplexml_load_string并使用属性函数来获取代码,但我总是得到一个空值。
$results = simplexml_load_string($response);
$errorCode = $results->attributes()->{'errors'};发布于 2016-08-14 05:03:18
您需要导航到具有所需属性的元素。有很多种方法。
echo $results->{'error-messages'}->errors['code'];//302因为只有一个error-messages和一个errors,所以它工作得很好。如果你有几个,你可以使用数组表示法来表示你想要的那个。因此下面这行代码也与302相呼应
echo $results->{'error-messages'}[0]->errors[0]['code'];您甚至可以使用xpath,一种遍历xml的查询语言。//将按名称返回所有节点:
echo $results->xpath('//errors')[0]->attributes()->code; //302echo显示了一个数字,但它仍然是一个对象。如果你想只捕获整数,就像这样转换它:
$errorCode = (int) $results->{'error-messages'}->errors['code'];看看这个really helpful intro。
https://stackoverflow.com/questions/38936901
复制相似问题