【问题标题】:How to receive xml requests and send response xml in php?如何在 php 中接收 xml 请求并发送响应 xml?
【发布时间】:2012-03-11 13:35:50
【问题描述】:

所以我需要构建一个将接收 xml 请求的应用程序,并在此基础上返回响应 xml。我知道如何发送请求和接收响应,但我从来没有这样做过。我会这样发送请求:

private function sendRequest($requestXML)
{
    $server = 'http://www.something.com/myapp';
    $headers = array(
    "Content-type: text/xml"
    ,"Content-length: ".strlen($requestXML)
    ,"Connection: close"
    );

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $server);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 100);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $data = curl_exec($ch);



    if(curl_errno($ch)){
        print curl_error($ch);
        echo "  something went wrong..... try later";
    }else{
        curl_close($ch);
    }

    return $data;

}

我的问题是 - 接收方的代码是什么?如何捕获传入的请求? 谢谢。

【问题讨论】:

    标签: php xml api


    【解决方案1】:

    一般的想法是读入 POST 值,将其解析为 XML,对其做出业务决策,根据您决定的 API 构建 XML 响应,并将其写入响应中。

    读入POST值:

    $dataPOST = trim(file_get_contents('php://input'));
    

    解析为 XML:

    $xmlData = simplexml_load_string($dataPOST);
    

    然后,您将构建一个 XML 字符串(或文档树,如果您愿意),并将其打印到响应中。 print() 或 echo() 都可以。

    【讨论】:

      【解决方案2】:

      您在接收端所要做的就是创建一个“普通”的 PHP 脚本。根据您的端点和请求服务之间的协议,您需要从最有可能是 $_GET$_POST 数组的正确位置获取数据。

      如果 $_POST 没有通过 原始 POST 数据,您可能需要阅读它,请阅读这篇文章

      http://www.codediesel.com/php/reading-raw-post-data-in-php/

      【讨论】:

        猜你喜欢
        • 2011-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-02
        • 1970-01-01
        • 2016-11-30
        相关资源
        最近更新 更多