PHP5已经支持soap了。可是不知怎么回事,网上的例子在我机器上总是通过不了。今天终于调通了,高兴!
PHP的SOAP很简单,首先建立一个函数文件soapfunc.php,这个文件包含了我们想通过SOAP协议暴露给Web services的函数:reverse,add2numbers和gettime,没有什么不同,就是普通的php函数,前两个就是网上到处都可以看到的,我自己又加了一个。这里,一定要注意规范php代码的格式,我的问题就是出在格式上了。
<?php
function reverse($str){
$retval = '';
if(strlen($str) < 1) {
return new SoapFault('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 SoapFault('Client','','The first number is invalid');
}
if (trim($num2) != intval($num2)) {
return new SoapFault('Client','','The second number is invalid');
}
return ($num1 + $num2);
}
function gettime(){
$time=strftime("%Y-%m-%d %H:%M:%S");
return $time;
}
?>
include_once('soapfunc.php');
$soap = new SoapServer(null,array('uri'=>"http://test-uri/"));
$soap->addFunction('reverse');
$soap->addFunction('add2numbers');
$soap->addFunction('gettime');
$soap->addFunction(SOAP_FUNCTIONS_ALL);
$soap->handle();
?>
最后,我们需要一个测试页面,来测一下我们的Web Service是否好用,soapclient.php
try {
$client = new SoapClient(null, array('location' =>
"[Your Website]/soapserver.php",'uri' => "http://test-uri/"));
$str = "This string will be reversed";
$reversed = $client->reverse($str);
echo "If you reverse '",$str,"', you get '",$reversed,"'
";
$n1=20;
$n2=33;
$sum = $client->add2numbers($n1,$n2);
echo "If you try ",$n1,"+",$n2,", you will get ",$sum,"
";
echo "The system time is: ",$client->gettime();
} catch (SoapFault $fault){
echo "Fault! code:",$fault->faultcode,", string: ",$fault->faultstring;
}
?>