php webservice SOAP

为了公开接口,被其他的应用程序调用,经常需要创建SOAP端,而在PHP中,SOAP的使用自从 PHP4就有了广泛的使用,开源的例如nosoap都是很不错的SOAP类,在PHP5开始,就已经支持SOAP了,在php_soap.dll(如果需要,请确定你的PHP5+的PHP.INI的SOAP扩展是打开的,并在phpinfo()中可以看到SOAP扩展。)

SOAP的使用有三个步骤:

1:创建您需要真正执行的程序,返回为一函数,例如需要查询当前的时间,我们创建获取目前时间的函数(可创建保存在soapfunction.php):
<?
/* 几个client端要调用的函数 */
    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 = date('Y-m-d H:i:s',time());
        return $time;
    }
?>

2:然后创建一个SOAPServer(可以创建于soapserver.php):
<?
    //先创建一个SoapServer对象实例,然后将我们要暴露的函数注册,最后的handle()用来处理接受的soap请求
    include_once('soapfunc.php');
    $soap = new SoapServer(null, array('uri'=>"httr://test-rui"));
    $soap->addFunction('reverse');
    $soap->addFunction('add2numbers');
    $soap->addFunction('gettime');
    $soap->addFunction(SOAP_FUNCTIONS_ALL);
    $soap->handle();
?>

以上代码第一行是包含了soap要执行的文件,第二行创建了一个SoapServer类,该类的第一个参数是wsdl,第二个参数是uri,php自带目前不支持自动生成wsdl,这个构造函数如果第一个参数是null,第二个是必填的,第二个参数就是命名空间,这是为了保证互联网WebServer的一致性和开发的一致性而产生的,你可以写入任何你想要的地址,无论存在与否。

3:客户端访问(可以创建soapclient.php):
<?
/*this is client ---test page*/
    try {
        $client = new SoapClient(null,array('location'=>"http://localhost/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 "<br>";
        echo "if you try $n1 + $n2 ,you will get $sum";
        echo "<br>";
        echo "The system time is :".$client->gettime();
    }

    catch(SoapFault $fault) {
        //echo "Fault!code:".$fault->faultcode."  string:".$fault->faultstring;
    }
?>


这里第一行市创建一个SoapClent,第一个参数还是wsdl,这里为null,第二个参数中必须包含命名空间(uri),这两个参数都要和需要访问的SoapServer一致,而执行地址(location)为SoapServer的php访问地址。

访问soapclient.php,将返回(类似):
if you reverse This string will be reversed,you get desrever eb lliw gnirts sihT
if you try 20 + 33 ,you will get 53
The system time is :2009-01-22 03:32:55
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值