如何在php中接收xml请求并发送响应xml? [英] How to receive xml requests and send response xml in php?

查看:46
本文介绍了如何在php中接收xml请求并发送响应xml?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I need to build an application that will receive xml request and based on that I will have to return the response xml. I know how to send requests and receive the response, but I have never done it the other way. I would send the request like so:

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;

}

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

My question is - what would be the code on the receiving side? How do I catch the incoming request? Thanks.

推荐答案

总体思路是读入 POST 值,将其解析为 XML,对其做出业务决策,根据您的 API 构建 XML 响应已决定,并将其写入响应中.

The general idea is to read in the POST value, parse it as XML, make a business decision on it, build out an XML response according to the API you've decided on, and write it into the response.

读入 POST 值:

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

解析为 XML:

$xmlData = simplexml_load_string($dataPOST);

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

Then, you would build out an XML string (or document tree, if you wish), and print it out to the response. print() or echo() will do fine.

这篇关于如何在php中接收xml请求并发送响应xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆