首頁  >  文章  >  後端開發  >  詳細介紹PHP開發Web服務的範例程式碼

詳細介紹PHP開發Web服務的範例程式碼

黄舟
黄舟原創
2017-03-13 16:36:553152瀏覽

PHP開發Web服務

WSO2 WSF/PHP(WSO2 Web Services Framework/PHP,WSO2 Web服務框架) 是PHP擴展,允許用來建立和使用Web服務。它支援SOAP1.1、SOAP1.2、MTOM、Web服務尋址、Web服務安全,也支援REST風格的呼叫。 WSO2 WSF/PHP最新的版本(v2.0.0)剛發布。
下面是一個簡短的指南解釋瞭如何用WSO2 WSF/PHP擴充來建立一個簡單的計算器服務。
(假設:Apache HTTP伺服器已經安裝在你的機器上,而且你基本上熟悉在Apache伺服器上執行PHP腳本)

#第一步:安裝WSO2 WSF/PHP擴充
在Ubuntu下,有下列步驟:

1. apt-get install php5
2. apt-get install php5-dev
3. apt-get libapache2-mod-php5
3. apt-get install lib
xml
2
4. apt-get install libxml2-dev
5. 下载 WSF/PHP v2.0.0 并解压到一个目录
6. 在命令行访问该目录,以“root”执行下列命令:
./configure
make
make install
7.  /etc/init.d/apache2 restart

第二步:編寫計算機服務
建立一個名為CalculatorService.php的腳本,且放入Apache HTTP伺服器的web root(通常是/ var/www)。

<?php
function calculate($inMessage){
$simplexml = new SimpleXMLElement($inMessage->str);
$operand1  = $simplexml->param1[0];
$operand2  = $simplexml->param2[0];
$operation = $simplexml->param3[0];
if($operation != null)
{
    switch($operation)
    {
         case "add" : $result= $operand1 + $operand2; break;
         case "sub" : $result= $operand1 - $operand2; break;
         case "mul" : $result= $operand1 * $operand2; break;
         case "p" : $result= $operand1 / $operand2; break;
    }
}
$response = <<<XML
        <result>$result</result>
XML;
$returnMsg = new WSMessage($response);
return $returnMsg;
}
$service = new WSService(array("operations" => array("calculate")));
$service->reply();
?>

一旦部署後,可以從http://localhost:298c9bd6ad6e8c821dc63aa0473d6209/CalculatorService.php存取它。

第三步:編寫計算器客戶端
編寫一個客戶端,呼叫此計算器服務,並列印結果。
該腳本命名為CalculatorClient.php,且放入Apache HTTP伺服器的web root。
不要忘了改變Apache伺服器的連接埠(即http://www.php.cn/:81/CalculatorService.php)來匹配伺服器。

<?php
$requestPayload = <<<XML
<calculate>
<param1>100</param1>
<param2>43</param2>
<param3>add</param3>
</calculate>
XML;
try{
$message = new WSMessage($requestPayload,
            array("to" => "http://localhost:81/CalculatorService.php"));
$client = new WSClient();
$response = $client->request($message);    
echo "Answer : $response->str";
}
catch (Exception $e){   
if ($e instanceof WSFault){
  $fault = $e;
  printf("Soap Fault received. Code: &#39;%s&#39; .Reason: &#39;%s&#39;/n",
                  $fault->code, $fault->reason);
}else{
  printf("Exception occurred. Message: &#39;%s&#39;/n", $e->getMessage());
}
}
?>

第四步:存取服務
透過執行CalculatorClient.php存取服務,如下:
http://localhost: 

######

以上是詳細介紹PHP開發Web服務的範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!