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服务器的端口(即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: '%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中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号