PHP实现Web Service的SOAP实例详解
本示例详细解析了利用PHP构建Web Service的具体操作方式,旨在为开发者提供实用的参考代码与实践思路。
在动手编码前,需对Web Service的基本概念有初步认知。后续将通过两个极简案例进行演示,无论何种场景,Web Service的开发均离不开服务端(Server)与客户端(Client)的交互架构。
本次测试所依赖的运行环境配置如下:Apache服务器版本为2.2.11,PHP运行版本为5.2.10。
在进行测试之前,必须确保PHP配置文件已启用SOAP扩展支持,具体操作是在配置文件中添加或确认以下指令有效: 复制代码 代码如下:extension=php_soap.dll; 完成上述配置后,即可开始体验Web Service的功能。
首先是服务端代码 serverSoap.php 的实现: 复制代码 代码如下:$soap = new SoapServer(null,array('uri'=>"http://192.168.1.179/"));//This uri is your SERVER ip. $soap->addFunction('minus_func'); //Register the function $soap->addFunction(SOAP_FUNCTIONS_ALL); $soap->handle(); function minus_func($i, $j){ $res = $i - $j; return $res; } 接下来是客户端代码 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; } 以上展示了客户端直接调用服务端普通函数的示例,随后我们将进一步演示基于类的调用方式。
以下是基于类封装的服务端代码 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; } } 对应的客户端代码 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; }
期望上述关于PHP程序设计的内容能对各位读者有所助益。