[文章摘自:http://www.cnblogs.com/chance1/archive/2009/04/08/1431949.html。实例部分做了改动。]
php有两个扩展可以实现web service,一个是NuSoap,一个是php 官方的soap扩展,由于soap是官方的,所以我们这里以soap来实现web service.由于默认是没有打开soap扩展的,所以自己先看一下soap扩展有没有打开。
在soap编写web service的过程中主要用到了SoapClient,SoapServer,SoapFault三个类。
SoapClient类
这个类用来使用Web services。SoapClient类可以作为给定Web services的客户端。
它有两种操作形式:
* WSDL 模式
* Non-WSDL 模式
在WSDL模式中,构造器可以使用WSDL文件名作为参数,并从WSDL中提取服务所使用的信息。
non-WSDL模式中使用参数来传递要使用的信息。
SoapServer类
这个类可以用来提供Web services。与SoapClient类似,SoapServer也有两种操作模式:WSDL模式和non-WSDL模式。这两种模式的意义跟 SoapClient的两种模式一样。在WSDL模式中,服务实现了WSDL提供的接口;在non-WSDL模式中,参数被用来管理服务的行为。
在SoapServer类的众多方法中,有三个方法比较重要。它们是SoapServer::setClass(),SoapServer::addFunction()和SoapServer::handle()。
下面给出实例:
server.php
<?php
$s = new SoapServer(null, array("location"=>"http://localhost/codeLab/soap/server.php", "uri"=>"server.php"));
$s->setClass("PersonInfo");
$s->handle();
Class PersonInfo
{
/**
* 返回姓名
* @return string
*
*/
public function getName($name)
{
return "My Name is {$name}";
}
}
client.php
<?php
try
{
// If working in non-WSDL mode,
// the location and uri options must be set,
// where location is the URL of the SOAP server to send the request to,
// and uri is the target namespace of the SOAP service.
$soap = new SoapClient(null, array(
'location' => "http://localhost/codeLab/soap/server.php",
'uri' => 'server.php',
'login' => 'hywang', // authName
'password' => '123', // authPassword
));
// 两种调用方式,直接调用方法,和用__soapCall间接调用
$result1 = $soap->getName("hywang");
$result2 = $soap->__soapCall("getName", array(
new SoapParam("hywang", "userName")
));
echo $result1;
echo "<br />";
echo $result2;
}
catch(SoapFault $e)
{
echo 'Error: '.$e->getMessage();
}
catch(Exception $e)
{
echo 'Error: '.$e->getMessage();
}