PHP的SOAP原理及实现
1. 簡(jiǎn)介:
SOAP : (全稱Simple Object Access Protocol) 為交換數(shù)據(jù)的一種協(xié)議規(guī)范,該通信協(xié)議位于HTTP之上,以XML格式語言進(jìn)行數(shù)據(jù)互換,使用場(chǎng)景:如果各項(xiàng)目之間使用不用的開發(fā)語言要進(jìn)行數(shù)據(jù)互換,就需要一個(gè)互相都能通信的工具,WSDL,SOAP為此誕生
?
WSDL:?WSDL 指網(wǎng)絡(luò)服務(wù)描述語言 (Web Services Description Language),WSDL 是一種使用 XML 編寫的文檔。這種文檔可描述某個(gè) Web service。它可規(guī)定服務(wù)的位置,以及此服務(wù)提供的操作(或方法)。
?
2. 配置:
PHP的SOAP擴(kuò)展開啟及配置
WIn環(huán)境
打開PHP.ini ??extension=php_soap.dll去掉前面的分號(hào)
Linux環(huán)境
編譯時(shí)加上 ??--enable-soap
?
?
WSDL緩存類型 1為磁盤 ? 2為內(nèi)存
soap.wsdl_cache = 1
緩存文件保存位置
soap.wsdl_cache_dir = /tmp
開啟或關(guān)閉WSDL緩存功能,由于每次進(jìn)行SOAP都會(huì)有下載對(duì)方XML文檔的過程,也是其效率低下的原因
soap.wsdl_cache_enabled =1
緩存文件的最大數(shù)量
soap.wsdl_cache_limit
緩存文件生存時(shí)間
soap.wsdl_cache_ttl = 3600
?
3. 應(yīng)用實(shí)例:
a. 不使用wsdl的情況
服務(wù)端:
<span style="font-size:18px;"><?php
class testclass{
public function getName($name)
{
return "hello ".$name;
}
}
function getName($name)
{
return "hello ".$name;
}
$a = new SoapServer(null,array("uri"=>"index.php"));
$a->setClass("testclass"); //指定一個(gè)類中的所有方法
//$a->addFunction("test"); //指定單個(gè)方法
$a->handle(); //處理訪問</span>
?
?
uri為必填項(xiàng),客戶端的uri必須和服務(wù)端的保持一致
客戶端
?
<span style="font-size:18px;">try{
$client = new SoapClient(null, array("location"=>"http://localhost/instance/index.php","uri"=>"index.php"));
//echo $client->getName("getName"); //調(diào)用方法
echo $client->__soapCall ("getName",array("name")); //調(diào)用方法
}catch(Exception $e){
print_r($e->getMessage(),true);
}</span>
?
location為SOAP服務(wù)端訪問地址,uri與服務(wù)端保持一致
?
b. 使用WSDL方法
因使用wsdl之前需要手動(dòng)生成xml文件,手寫的話太過繁瑣,可使用SoapDiscovery.class.php 開源類生成
下載地址?
?
<span style="font-size:18px;"><?php
class testclass{
public function getName($name)
{
return "hello ".$name;
}
}
include_once "SoapDiscovery.class.php";
$discovery = new SoapDiscovery("testclass","testclass");
$filename = $discovery->getWSDL(); //生成XML文件
echo $filename;</span>
服務(wù)端
?
?
<span style="font-size:18px;">$a = new SoapServer("testclass.wsdl");
$a->setClass("testclass"); //指定一個(gè)類中的所有方法
$a->handle(); //處理訪問 </span>
客戶端
?
?
<span style="font-size:18px;">try{
$client = new SoapClient("http://localhost/instance/index.php?wsdl");
//echo <span style="font-family:Arial,Helvetica,sans-serif">$client</span>->getName("getName");
//echo <span style="font-family:Arial,Helvetica,sans-serif">$client</span><span style="font-family:Arial,Helvetica,sans-serif">->__soapCall ("getName",array("name"));</span>
print_r(<span style="font-family:Arial,Helvetica,sans-serif">$client</span><span style="font-family:Arial,Helvetica,sans-serif">->__getFunctions()); //打印服務(wù)端所有提供的方法</span></span>
<span style="font-size:18px;">}catch(Exception $e){
print_r($e->getMessage(),true);
}</span>
?
?
擴(kuò)展類所提供的方法可參考PHP Manual
來源:https://blog.csdn.net/marvinblog/article/details/14163557
總結(jié)
以上是生活随笔為你收集整理的PHP的SOAP原理及实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos安装php扩展soap实现w
- 下一篇: 民生银行账单怎么查