码迷,mamicode.com
首页 > Web开发 > 详细

[PHP]php发布和调用Webservice接口的案例

时间:2015-06-29 11:28:40      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

分两步走:1.服务端发布接口;2.客户端调用方法

1.服务端发布接口:

需要nusoap工具,下载地址:http://sourceforge.net/projects/nusoap/

下载完和要发布接口的php文件放在同一目录下。

服务端发布接口soapserver.php例子:

<?php
require_once(‘./lib/nusoap.php‘);
$soap = new soap_server;

$soap->soap_defencoding = ‘UTF-8‘;
$soap->decode_utf8 = false;
$soap->xml_encoding = ‘UTF-8‘;
$soap->configureWSDL(‘reverse‘,‘add2numbers‘);
//$server->configureWSDL(‘add2numbers‘);

$soap->register(‘reverse‘,
array(‘str‘ => ‘xsd:string‘),
array(‘return‘ => ‘xsd:string‘)
);
$soap->register(‘add2numbers‘,
array(‘num1‘ => ‘xsd:int‘,‘num2‘ => ‘xsd:int‘),
array(‘return‘ => ‘xsd:int‘)
);

//Check variable set?
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA)? $HTTP_RAW_POST_DATA:‘‘;

//service handle the client data
$soap->service($HTTP_RAW_POST_DATA);
//echo $server;
/*
* RPC function
* @param $name
*/
function reverse($str){
$retval = "";
if(strlen($str) < 1) {
return new soap_fault(‘Client‘,‘‘,‘Invalid string‘);
}
for ($i = 1; $i <= strlen($str); $i++) {
$retval .= $str[(strlen($str) - $i)];
}
return $retval;
}

function add2numbers($num1, $num2) {
if (trim($num1) != intval($num1)) {
return new soap_fault(‘Client‘, ‘‘, ‘The first number is invalid‘);
}
if (trim($num2) != intval($num2)) {
return new soap_fault(‘Client‘, ‘‘, ‘The second number is invalid‘);
}
return ($num1 + $num2);
}
?>

发布的结果截图:

 技术分享

 wsdl的说明截图:

技术分享

 

2.客户端调用接口:

调用接口soapclient.php例子:

<?php
require_once "./lib/nusoap.php";

$client = new nusoap_client("http://192.168.119.21/soapserver.php");
$client->soap_defencoding = ‘UTF-8‘;
$client->decode_utf8 = false;
$client->xml_encoding = ‘UTF-8‘;

$str = "This string will be reversed";
$params1 = array(‘str‘=>$str);
$reversed = $client->call(‘reverse‘,$params1);
echo "If you reverse ‘$str‘, you get ‘$reversed‘<br>\n";

$n1 = 5;
$n2 = 14;
$params2 = array(‘num1‘=>$n1, ‘num2‘=>$n2);
$added = $client->call(‘add2numbers‘, $params2);
echo "If you add $n1 and $n2 you get $added<br>\n";
?>

调用后结果:

技术分享

[PHP]php发布和调用Webservice接口的案例

标签:

原文地址:http://www.cnblogs.com/liangxuehui/p/4606935.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!