php中soap 的使用实例无需手写WSDL文件,提供自动生成WSDL文件类

在这里先介绍标准的webservice。 
那么如何创建wsdl呢?对于PHP来说这确实是件很不容易的事情,有人说用zend studio创建很方便,这是一种方法。但对于那些不喜欢用zend studio的人来说,会觉得创建一个web service还要安装zend studio,太强人所难了。
    在这里介绍一个简单的方法,到网上下载SoapDiscovery.class.php类,里面有个公用方法:getWSDL,这个方法末尾是用的return,那么,你修改一下这个方法: 
//return sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>'); 
//生成wsdl文件,将上面的return注释 
$fso = fopen($this->class_name . ".wsdl" , "w"); 
fwrite($fso, sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>')); 
现在生成wsdl的类有了,SoapDiscovery.class.php(源码在最末尾)。

     再准备一个提供服务的Service.php类文件或者函数就可以创建wsdl了!

复制代码
<?php class Service {      
public function HelloWorld() {
         return "Hello";     
}     
 public function Add($a, $b) {
         return $a + $b;     
}  
} ?> 
复制代码

  创建wsdl文件的creat_wsdl.php

复制代码
<?php  
include("Service.php"); 
include("SoapDiscovery.class.php");
$disco = new SoapDiscovery('Service', 'soap'); //第一个参数是类名(生成的wsdl文件就是以它来命名的),即Service类,第二个参数是服务的名字(这个可以随便写)。 
$disco->getWSDL();
复制代码

  运行create_wsdl.php文件,此时会生成一个Service.wsdl的文件



  再在Service.php文件中添加一些代码

复制代码
<?php  class Service {      
public function HelloWorld() {
         return "Hello";     
}      
public function Add($a, $b) {
         return $a + $b;     
}  
}  
$server = new SoapServer('Service.wsdl', array('soap_version' => SOAP_1_2));
 $server->setClass("Service"); //注册Service类的所有方法  
$server->handle(); //处理请求   
?> 
复制代码

  创建webservice客户端程序,测试webservice是否有效,文件名是:client.php 
将以下内容拷贝进去:

  

复制代码
<?php   ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存    $soap = new SoapClient('http://localhost/Dragon/soap/Service.php?wsdl');
 echo $soap->Add(28, 2);
echo $soap->__soapCall('Add',array(28,2))//或这样调用
 
复制代码

  OK!测试通过!

  

 二、无WSDL文件方式

   服务器端


<?php
class Service
{
  public function HelloWorld()
   {
      return  "Hello";
   }
  public  function Add($a,$b)
   {
      return $a+$b;
   }
}
$server=new SoapServer(null,array('uri' => "abcd"));
$server->setClass("Service");
$server->handle();

   客户端


<?php
  try {
  $soap = new SoapClient(nullarray(
  "location" => "http://localhost/Dragon/soap/Service.php",
  "uri" => "abcd", //资源描述符服务器和客户端必须对应
  "style" => SOAP_RPC,
  "use" => SOAP_ENCODED
  ));

  echo $soap->Add(12, 2);
  } catch (Exction $e) {
  echo print_r($e->getMessage(), true);
  }

  

三.出现的问题。

1.在方法中对属性的赋值在其他方法中不起作用。
比如在客户端调用服务端某个方法对某个属性赋值。
在其他方法里就不能用。但在 __construct 方法中对属性的赋值是可以个在其他方法中使用的。

2. 提示 Client] looks like we got no XML document错误。
服务器端文件在<?php ?> 标签前后都不要有任何数据包括空格,空行。

3. Warning: SoapClient::SoapClient(): I/O warning : failed to load external entity
原因如下:PHP程序作为 SOAP客户端 采用 WSDL 模式访问远端服务器的时候,PHP是通过调用 libcurl 实现的。至少在 PHP5.2.X 是这样的。如果采用 non-WSDL 模式,就不需要 libcurl。除了 了ibcurl以外,至少还关联的库包括:libidn,ibgcc,libiconv,libintl,openssl

 

现在,你已经解决你了系统接口的问题了!剩下的空余时间,就有必要去了解什么是SOAP、http协议、XML了!

 

SoapDiscovery.class.php 文件

View Code 

<?php

/**
 * Copyright (c) 2005, Braulio Jos?Solano Rojas
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 * 
 *     Redistributions of source code must retain the above copyright notice, this list of
 *     conditions and the following disclaimer. 
 *     Redistributions in binary form must reproduce the above copyright notice, this list of
 *     conditions and the following disclaimer in the documentation and/or other materials
 *     provided with the distribution. 
 *     Neither the name of the Solsoft de Costa Rica S.A. nor the names of its contributors may
 *     be used to endorse or promote products derived from this software without specific
 *     prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 *
 * @version $Id$
 * @copyright 2005 
 
*/

/**
 * SoapDiscovery Class that provides Web Service Definition Language (WSDL).
 * 
 * @package SoapDiscovery
 * @author Braulio Jos?Solano Rojas
 * @copyright Copyright (c) 2005 Braulio Jos?Solano Rojas
 * @version $Id$
 * @access public
 * 
*/
class SoapDiscovery {

    private $class_name = '';
    private $service_name = '';

    /**
     * SoapDiscovery::__construct() SoapDiscovery class Constructor.
     * 
     * @param string $class_name
     * @param string $service_name
     * 
*/
    public function __construct($class_name = '', $service_name = '') {
        $this->class_name = $class_name;
        $this->service_name = $service_name;
    }

    /**
     * SoapDiscovery::getWSDL() Returns the WSDL of a class if the class is instantiable.
     * 
     * @return string
     * 
*/
    public function getWSDL() {
        if (empty($this->service_name)) {
            throw new Exception('No service name.');
        }
        $headerWSDL = "<?xml version=\"1.0\" ?>\n";
        $headerWSDL.= "<definitions name=\"$this->service_name\" targetNamespace=\"urn:$this->service_name\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"urn:$this->service_name\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\">\n";
        $headerWSDL.= "<types xmlns=\"http://schemas.xmlsoap.org/wsdl/\" />\n";

        if (empty($this->class_name)) {
            throw new Exception('No class name.');
        }

        $class = new ReflectionClass($this->class_name);

        if (!$class->isInstantiable()) {
            throw new Exception('Class is not instantiable.');
        }

        $methods = $class->getMethods();

        $portTypeWSDL = '<portType name="' . $this->service_name . 'Port">';
        $bindingWSDL = '<binding name="' . $this->service_name . 'Binding" type="tns:' . $this->service_name . "Port\">\n<soap:binding style=\"rpc\" transport=\"http://schemas.xmlsoap.org/soap/http\" />\n";
        $serviceWSDL = '<service name="' . $this->service_name . "\">\n<documentation />\n<port name=\"" . $this->service_name . 'Port" binding="tns:' . $this->service_name . "Binding\"><soap:address location=\"http://" . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF'] . "\" />\n</port>\n</service>\n";
        $messageWSDL = '';
        foreach ($methods as $method) {
            if ($method->isPublic() && !$method->isConstructor()) {
                $portTypeWSDL.= '<operation name="' . $method->getName() . "\">\n" . '<input message="tns:' . $method->getName() . "Request\" />\n<output message=\"tns:" . $method->getName() . "Response\" />\n</operation>\n";
                $bindingWSDL.= '<operation name="' . $method->getName() . "\">\n" . '<soap:operation soapAction="urn:' . $this->service_name . '#' . $this->class_name . '#' . $method->getName() . "\" />\n<input><soap:body use=\"encoded\" namespace=\"urn:$this->service_name\" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" />\n</input>\n<output>\n<soap:body use=\"encoded\" namespace=\"urn:$this->service_name\" encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" />\n</output>\n</operation>\n";
                $messageWSDL.= '<message name="' . $method->getName() . "Request\">\n";
                $parameters = $method->getParameters();
                foreach ($parameters as $parameter) {
                    $messageWSDL.= '<part name="' . $parameter->getName() . "\" type=\"xsd:string\" />\n";
                }
                $messageWSDL.= "</message>\n";
                $messageWSDL.= '<message name="' . $method->getName() . "Response\">\n";
                $messageWSDL.= '<part name="' . $method->getName() . "\" type=\"xsd:string\" />\n";
                $messageWSDL.= "</message>\n";
            }
        }
        $portTypeWSDL.= "</portType>\n";
        $bindingWSDL.= "</binding>\n";
        //return sprintf('%s%s%s%s%s%s', $headerWSDL, $portTypeWSDL, $bindingWSDL, $serviceWSDL, $messageWSDL, '</definitions>');
        //生成wsdl文件,将上面的return注释

        $fso = fopen($this->class_name . ".wsdl", "w");
        fwrite($fsosprintf('%s%s%s%s%s%s', $headerWSDL$portTypeWSDL$bindingWSDL$serviceWSDL$messageWSDL, '</definitions>'));
    }

    /**
     * SoapDiscovery::getDiscovery() Returns discovery of WSDL.
     * 
     * @return string
     * 
*/
    public function getDiscovery() {
        return "<?xml version=\"1.0\" ?>\n<disco:discovery xmlns:disco=\"http://schemas.xmlsoap.org/disco/\" xmlns:scl=\"http://schemas.xmlsoap.org/disco/scl/\">\n<scl:contractRef ref=\"http://" . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF'] . "?wsdl\" />\n</disco:discovery>";
    }

}

?>
原文地址:https://www.cnblogs.com/rooney/p/2580875.html