Web Services Tu...login
Web Services Tutorial
author:php.cn  update time:2022-04-11 14:41:17

Web service instance



Any application can have a Web Service component.

The creation of Web Service has nothing to do with the type of programming language.

In this chapter we will introduce how to use PHP's SOAP extension to create a Web Service.

SOAP has two operation modes, NO-WSDL and WSDL.

  • NO-WSDL mode: Use parameters to pass the information to be used.

  • WSDL Mode: Uses the WSDL file name as a parameter and extracts the information required by the service from the WSDL.


An example: PHP Web Service

Before starting the example, we need to determine whether PHP has the SOAP extension installed. Check phpinfo. The following information appears to indicate that the SOAP extension has been installed:

In this example, we will use PHP SOAP to create a simple Web Service.

ServerServer.php The file code is as follows:

<?php 
// SiteInfo 类用于处理请求
Class SiteInfo
{
    /**
     *    返回网站名称
     *    @return string 
     *
     */
    public function getName(){
        return "php中文网";
    }

    public function getUrl(){
        return "www.php.cn";
    }
}

// 创建 SoapServer 对象
$s = new SoapServer(null,array("location"=>"http://localhost/soap/Server.php","uri"=>"Server.php"));

// 导出 SiteInfo 类中的全部函数
$s->setClass("SiteInfo");
// 处理一个SOAP请求,调用必要的功能,并发送回一个响应。
$s->handle();
?>

ClientClient.php The file code is as follows:

<?php
try{
  // non-wsdl方式调用web service
  // 创建 SoapClient 对象
  $soap = new SoapClient(null,array('location'=>"http://localhost/soap/Server.php",'uri'=>'Server.php'));
  // 调用函数 
  $result1 = $soap->getName();
  $result2 = $soap->__soapCall("getUrl",array());
  echo $result1."<br/>";
  echo $result2;
} catch(SoapFault $e){
  echo $e->getMessage();
}catch(Exception $e){
  echo $e->getMessage();
}


php.cn