使用/ PHP从XML响应中提取数据

时间:2013-08-01 17:38:11

标签: php xml variables simplexml

当我收到包含以下内容的API响应时:

<?xml version="1.0" encoding="utf-8"?>
<response xmlns="http://www.XXXXXXX.com/api/" status="ok">
  <client_id>17992</client_id>
</response>

我可以使用此功能获得<client_id>的结果。

$xml = simplexml_load_string($server_output);
$client = (string) $xml->client_id;
echo $client; // produces 17992 in this case

但如果我在下面添加,我没有为$ response分配值。

$response = (string) $xml->response; // produces empty value

如何编写PHP代码以检查XML响应“status”= OK?

2 个答案:

答案 0 :(得分:1)

simplexml的简单应用上看到这一点:
http://www.php.net/manual/en/simplexml.examples-basic.php

要访问节点的属性,请执行以下操作:

$xml = simplexml_load_string($x); // assume XML in $x
echo $xml['status'];

或循环遍历所有属性:

foreach ($xml->attributes() as $name => $value)
    echo "$name: $value <br />";

在行动中看到它:https://eval.in/40185

答案 1 :(得分:0)

这应该对你有用:)

$xml['status'];