详细介绍PHP开发Web服务的示例代码

黄舟
黄舟 原创
2023-03-06 15:28:02 2776浏览

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:<port>/CalculatorService.php访问它。

第三步:编写计算器客户端
编写一个客户端,调用此计算器服务,并打印结果。
该脚本命名为CalculatorClient.php,且放入Apache HTTP服务器的web root。
不要忘了改变Apache服务器的端口(即//m.sbmmt.com/: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: '%s' .Reason: '%s'/n",
                  $fault->code, $fault->reason);
}else{
  printf("Exception occurred. Message: '%s'/n", $e->getMessage());
}
}
?>

第四步:访问服务
通过执行CalculatorClient.php访问服务,如下:
http://localhost:<port>/CalculatorService.php

以上就是详细介绍PHP开发Web服务的示例代码的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。