php webservice实例(转载)

首先大家要简单了解了何谓webservice,接下来就做两个非常简单的例子,webservice还是逃不开server端(服务器端) 与client端(客户端) 。

做这个测试之前,要确认你的php配置文件中已经将soaps扩展打开,即extension=php_soap.dll;

//server端 serverSoap.php(客户端的serverSoap.php)

$soap = new SoapServer(null,array('uri'=>"http://192.168.1.179/"));//This uri is your SERVER ip.(这个uri是你的服务器的ip)

$soap->addFunction('minus_func');                                                 //Register the function(注册函数)(http://php.chinaunix.net/manual/zh/function.soap-soapserver-addfunction.php)添加输出函数

 $soap->addFunction(SOAP_FUNCTIONS_ALL);       

$soap->handle();

function minus_func($i, $j){
    $res = $i - $j;
    return $res;
}
(普通的方法写法,参数,return)

前面这些是将 函数添加到服务器端的过程

//client端 clientSoap.php(客户端的clientSoap.php)
try {
    $client = new SoapClient(null,
        array('location' =>"http://192.168.1.179/test/serverSoap.php",'uri' => "http://127.0.0.1/")
    );
    echo $client->minus_func(100,99); 

} catch (SoapFault $fault){
    echo "Error: ",$fault->faultcode,", string: ",$fault->faultstring;
}
PHP中try{}catch{}是异常处理.将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$fault收集错误信息和显示.

<------------------------------------------------------------>
这是客户端调用服务器端函数的例子,我们再搞个class的。

//server端 serverSoap.php
$classExample = array();
$soap = new SoapServer(null,array('uri'=>"http://192.168.1.179/",'classExample'=>$classExample));

$soap->setClass('chesterClass');      //从指定的类输出所有方法

$soap->handle();

class chesterClass {
    public $name = 'Chester';

    function getName() {
        return $this->name;
    }
}
//client端(客户端) clientSoap.php
try {
    $client = new SoapClient(null,
        array('location' =>"http://192.168.1.179/test/serverSoap.php",'uri' => "http://127.0.0.1/")
    );
    echo $client->getName();

} catch (SoapFault $fault){
    echo "Error: ",$fault->faultcode,", string: ",$fault->faultstring;
}

转自 http://www.cnblogs.com/wuhenke/archive/2010/09/30/1839424.html

原文地址:https://www.cnblogs.com/zhaoyang-1989/p/3367790.html