从 xml 文件 php 获取属性

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>

我正在使用 simplexml_load_string 并使用属性函数来获取代码,但我一直得到一个空值。

 $results = simplexml_load_string($response);

 $errorCode = $results->attributes()->{'errors'};

您需要导航到具有所需属性的元素。方法很多。

echo $results->{'error-messages'}->errors['code'];//302

这很好用,因为只有一个 error-messages 和一个 errors。如果你有多个,你可以使用数组表示法来指示你想要的那个。所以下面这行也呼应 302

echo $results->{'error-messages'}[0]->errors[0]['code'];

您甚至可以使用 xpath 一种查询语言来遍历 xml。 // 将 return 所有节点的名称:

echo $results->xpath('//errors')[0]->attributes()->code; //302

echo 显示一个数字,但它仍然是一个对象。如果您只想捕获整数,请像这样转换它:

$errorCode = (int) $results->{'error-messages'}->errors['code'];

看看这个 really helpful intro