使用属性值选择xml元素

时间:2014-05-28 09:53:10

标签: php xpath

<?xml version='1.0'?> 
<error>
<error_detail code="0">Successfully</error_detail>
<error_detail code="1">Invalid Username or Password</error_detail>
<error_detail code="2">No username or password</error_detail>
<error_detail code="3">Session has expired</error_detail>
<error_detail code="4">Date of effectivity cannot be less than</error_detail>
</error>

如何使用xpath获取“会话已过期”?

我试过了:

$xml   = simplexml_load_string($xml_string);
$a     = $xml->xpath("//error_detail[@code='3']");
display_output($a);

我得到了这个:

array ( 0 => SimpleXMLElement::__set_state(array( '@attributes' => array ( 'code' => '53', ), )), )

1 个答案:

答案 0 :(得分:1)

即使查询只返回一个元素,xpath查询也会返回一个数组。您需要将此第一个元素转换为字符串才能获得文本值:

$xml   = simplexml_load_string($xml_string);
$a     = $xml->xpath("//error_detail[@code=3]");

// convert to string though . ''
var_dump($a[0] . ''); // string(19) "Session has expired"