2014年2月15日 星期六

PHP建立簡單的Webservice




1.網路上先下載SoapDiscovery.class.php

將getWSDL()函式的最後一行做更改

//註解原程式碼
//return sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>');
//加上
$fso = fopen($$this->class_name . ".wsdl", "w");
fwrite($fso, sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>'));

註:AGA說 </definitions> 搞了他一個下午,記得要加!



2.創建一個提供服務的類或函數

//webservice.php,簡單的加號算術和helloworld
<?php
class service{
    public function add($a,$b){
        return $a + $b;
    }
    publice function helloworld(){
        return "HelloWorld";
    }
}
?>



3.創建建立WSDL的文件


//creat_wsdl.php
<?php
    //加入剛剛件的服務和SoapDiscovery.class.php
    include ("webservice.php");
    include ("SoapDiscovery.class.php");
    //第一個參數是wsdl的檔名,第二個參數是service的名字可自訂
    $c = new SoapDiscovery ('service','soap');
    $c->getWSDL();
?>
4.執行剛剛完成的creat_wsdl.php建立WSDL
http://localhost/ws_test/creat_wsdl.php
此時會產生wsdl檔

5.在剛剛創建的webservice.php加上
$server = new SoapServer('service.wsdl', array('soap_version' => SOAP_1_2)); 
$server->setClass("service"); 
$server->handle();

6.建立client端測試

//client
<?php
$client = new SoapClient("http://localhost/ws_test/webservice_.php?wsdl");
echo $client->add(12,13);
?>
執行結果會是25
參考網址:
http://blog.xuite.net/hankohya34/blog/82821149-PHP%E5%BB%BA%E7%AB%8BWebService
http://rritw.com/a/bianchengyuyan/PHP/20111208/150662.html
http://wenku.it168.com/d_000783064.shtml