PHP SOAP终于测验成功[ZT]
PHP SOAP终于测验成功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;
}
?>
--------------------------------------------------------------------------------
然后,编写soapserver.php,这个文件首先创建一个SoapServer对象实例,然后将我们要暴露的函数注册,最后的handle()用来处理接受到的SOAP请求。网上好多代码里面都没有这一行。
--------------------------------------------------------------------------------
<?
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' =>
"http://localhost/phpsite/soap/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;
}
?>
--------------------------------------------------------------------------------
测试页面首先创建一个SoapClient的实例,指定了该服务的URL和URI,SoapClient的构造函数第一个参数本应是指定WSDL(描述Web服务的公共接口)描述文件的,本来我也没看过WSDL的写法,所以就不采用wsdl方式定义了。
创建完SoapClient以后,就可以像本地函数一样调用Web Services了。
原文地址:http://www.nkstars.org/archive/beat/000520.html
页:
[1]