使用 php 处理 xml 响应

Handle xml response with php

我正在使用下面的代码来获取 xml 数据。我无法以任何其他方式做到这一点,因为我将它用于我的 iOS 应用程序并且我收到的响应是 xml 元素,正如我所期望的那样。当我在浏览器中 运行 它时,我只看到 xml 节点的值。

例如这是我的 xml:

<Message version="1.0" messageId="12">
<SaleResponse>
<OrderId>1234</OrderId>
<OrderAmount>1.0</OrderAmount>
</SaleResponse>
</Message>

这正是我在 ios 应用程序中获得的输出,但在我的浏览器中我得到的是:

12341.0

这是我的 php 代码:

<?php

      $url = 'https://something.com';

            $ch = curl_init($url);

            $inp = $_REQUEST["xmlpost"];

            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                               'Content-type: application/xml',
                               'TX_URL: something.com',
                               'TX_TokenExID: something',
                               'TX_APIKey: something' ));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $inp);

            $result = curl_exec($ch);

            echo $result;
    ?>

那么如何将 result 处理为 xml 并分别获取每个标签?

提前致谢

运行 你的字符串通过 php 函数 simplexml_load_string:

$result = simplexml_load_string($result);
echo $result->SaleResponse->OrderId


<?php
//or in an actual example

$string = '<Message version="1.0" messageId="12">
<SaleResponse>
<OrderId>1234</OrderId>
<OrderAmount>1.0</OrderAmount>
</SaleResponse>
</Message>';
$obj= simplexml_load_string($string);
echo '<pre>';
print_r($obj);