2011-07-21 163 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工作。 –