php 如何在php中接收xml请求并发送响应xml?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9374224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to receive xml requests and send response xml in php?
提问by bukowski
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:
因此,我需要构建一个接收 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;
}
My question is - what would be the code on the receiving side? How do I catch the incoming request? Thanks.
我的问题是 - 接收方的代码是什么?如何捕获传入的请求?谢谢。
回答by Jordan
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 值,将其解析为 XML,对其做出业务决策,根据您决定的 API 构建 XML 响应,并将其写入响应中。
Read in the POST value:
读入 POST 值:
$dataPOST = trim(file_get_contents('php://input'));
Parse as XML:
解析为 XML:
$xmlData = simplexml_load_string($dataPOST);
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.
然后,您将构建一个 XML 字符串(或文档树,如果您愿意),并将其打印到响应中。print() 或 echo() 会很好。
回答by quickshiftin
All you have to do on the receiving end is create a 'normal' PHP script. Depending on the protocol between your endpoint and the requesting service you need to grab the data from the correct location which is most likely going to be a $_GETor $_POSTarray.
您在接收端要做的就是创建一个“正常”的 PHP 脚本。根据端点和请求服务之间的协议,您需要从正确的位置获取数据,这很可能是$_GET或$_POST数组。
You may have to read the rawPOST data if it's not coming through in $_POST, take a peak at this article
如果 $_POST 中没有通过原始POST 数据,您可能需要阅读原始POST 数据,请阅读本文