在PHP(和/或Zend Framework)中解析XML响应

时间:2022-10-09 23:17:25

I am using the Zend Framework and using Zend_Http_Client to make a POST request to a third party API.

我正在使用Zend Framework并使用Zend_Http_Client向第三方API发出POST请求。

$client = new Zend_Http_Client('http://api.com');
$client->setParameterPost(array(
    'param1' => 'value'
));
$response = $client->request('POST');
echo $response->getBody();

This API returns an XML document as its response.

此API返回XML文档作为其响应。

<?xml version="1.0" ?>
<registration>
    <id>12345</id>
</registration>

How can I turn the response into something I can work with?

如何将响应转换为可以使用的内容?

3 个解决方案

#1


13  

I find the easiest way is to use SimpleXml

我发现最简单的方法是使用SimpleXml

$data = simplexml_load_string($response->getBody());

$ data = simplexml_load_string($ response-> getBody());

Then, to get the ID, you can use

然后,要获取ID,您可以使用

$id = (string) $data->registration->id;

$ id =(string)$ data-> registration-> id;

#2


2  

for xml file from url, you can use below code.

对于来自url的xml文件,您可以使用下面的代码。

$xml = simplexml_load_file('any url here');

echo $xml->id;

#3


1  

Is it XMLRPC? Look into Zend_XmlRpc. Otherwise: see Pekka's link in the comment on the Question, or use Zend_Config_Xml (not really what its intended for, though)

是XMLRPC吗?查看Zend_XmlRpc。否则:在问题的评论中查看Pekka的链接,或者使用Zend_Config_Xml(虽然不是它的目的)

#1


13  

I find the easiest way is to use SimpleXml

我发现最简单的方法是使用SimpleXml

$data = simplexml_load_string($response->getBody());

$ data = simplexml_load_string($ response-> getBody());

Then, to get the ID, you can use

然后,要获取ID,您可以使用

$id = (string) $data->registration->id;

$ id =(string)$ data-> registration-> id;

#2


2  

for xml file from url, you can use below code.

对于来自url的xml文件,您可以使用下面的代码。

$xml = simplexml_load_file('any url here');

echo $xml->id;

#3


1  

Is it XMLRPC? Look into Zend_XmlRpc. Otherwise: see Pekka's link in the comment on the Question, or use Zend_Config_Xml (not really what its intended for, though)

是XMLRPC吗?查看Zend_XmlRpc。否则:在问题的评论中查看Pekka的链接,或者使用Zend_Config_Xml(虽然不是它的目的)