為了公開接口,被其他的應用程式調用,經常需要建立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