2011-07-21 165 views
1

我想从也支持php的webserver返回一个xml文档。 这是类似于传统的Web服务,但我想在PHP中实现它。这甚至有可能吗?php - 发送和接收xml文档

为了更具体地了解我的需求 - 我想发送一个xml文档作为请求到服务器,让PHP对它做一些处理并发回给我一个xml文档作为响应。

在此先感谢。

+0

http://stackoverflow.com/questions/471506/post-xml-to-url-with-php-and-handle -response – Devon

回答

4

也许你只是想要http://php.net/SOAP

如果不是SOAP,那么您可以发送您的XML POST请求并使用$xml = file_get_contents('php://input');将其转储到您可以提供给http://php.net/DOM或其他XML处理器的变量中。

处理完毕后,您将header('Content-Type: text/xml');(或application/xml)并输出修改后的XML文档。

+1

为什么不使用['http_get_request_body'](http://www.php.net/manual/en/function.http-get-request-body.php)和另一个['http_get_request_ *'函数家族](http://www.php.net/manual/en/ref.http.php)而不是'php:// input'? – prodigitalson

+1

因为这些不是标准功能;他们需要一个可能无法使用的PECL模块。 php://输入无处不在。 –

+0

+1 ......确实如此,除非它是一个内联网,否则它应该是一个非问题。我还没有部署到一个主机,从2000年以来不允许安装PECL扩展或PEAR软件包。 – prodigitalson

-1

使用卷曲。

//open connection 
$ch = curl_init(); 

//set the url, number of POST vars, POST data 
curl_setopt($ch,CURLOPT_URL,$url); 
curl_setopt($ch,CURLOPT_POST,1); 
curl_setopt($ch,CURLOPT_POSTFIELDS,$xmlString); 

//execute post 
$result = curl_exec($ch); 
0

超级简单的读取XML请求体例如:

$request = http_get_request_body(); 
if($request && strpos($request, '<?xml') !== 0){ 
    // not XML do somehting appropriate 
} else { 
    $response = new DomDocment(); // easier to manipulate when *building* xml 
    $requestData = DomDocument::load($request); 
    // process $requestData however and build the $response XML 

    $responseString = $response->saveXML(); 
    header('HTTP/1.1 200 OK'); 
    header('Content-type: application/xml'); 
    header('Content-length: ', strlen($responseString)); 
    print $responseString; 
    exit(0); 

} 
+0

我看到“调用未定义的函数http_get_request_body()”服务器报告的错误。我正在运行PHP版本5.2.17,我可以访问phpinfo(),但我不确定需要什么模块才能使服务器停止抱怨http_get_request_body()未找到。谢谢 –

+0

你需要['pecl_http'](http://www.php.net/manual/en/book.http.php)。或者,你可以用'Tino]建议的'file_get_contents('php:// input')'替换那个调用(http://stackoverflow.com/questions/6779320/php-send-and-receive-xml-文件/ 6779443#6779443) – prodigitalson

+0

谢谢。但我不认为我的托管服务已经安装了pecl_http模块。我发现pecl的唯一参考是sqlite。但是file_get_contents API工作。 –