search
HomeBackend DevelopmentPHP TutorialHow to use PHP to implement a WebService_PHP tutorial

WSDL

WSDL (Web Services Description Language) is an XML-based language used to describe Web Services and how to access them. This document describes a Web service. It specifies the location of the service and the operations (or methods) provided by this service.

The main structure of a WSDL document is similar to this:

<definitions>
	<types>
	   definition of types........
	</types>
	<message>
	   definition of a message....
	</message>
	<portType>
	   definition of a port.......
	</portType>
	<binding>
	   definition of a binding....
	</binding>
</definitions>

The WSDL document can contain other elements, such as extension elements, and a service element, which can combine the definitions of several web services into a single WSDL document.

PHP generates WSDL

Class code (SoapDiscovery.class.php):

<?php
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>');
    }
    
    /**
     * 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>";
    }
}
 
?>

Usage (server server.php):

<?php
define('WSDL_URL','hello.wsdl');        //定义WSDL文件路径
ini_set('soap.wsdl_cache_enabled','0');    //关闭WSDL缓存
 
//WSDL文件不存在时自动创建
if(!file_exists(WSDL_URL))
{
    require_once 'SoapDiscovery.class.php';
    $disco = new SoapDiscovery('HelloWorld','IELIWB_HelloWorld');
    $str = $disco->getWSDL();
    file_put_contents(WSDL_URL,$str);
}
 
//SOAP开启并接收Client传入的参数响应 
$server = new SoapServer(WSDL_URL);
$server->setClass('HelloWorld');
$server->handle();
 
 
//测试定义公开的类
class HelloWorld {
    private $nombre = '';
    public function __construct($name = 'World') {$this->name = $name;}
    public function greet($name = '') {$name = $name?$name:$this->name;return 'Hello '.$name.'.';}
    public function serverTimestamp() {return time();} 
}
?>

Client client.php:

<?php
$client = new SoapClient("http://127.0.0.1/createsoap/hello.wsdl");
 
try {
        $result = $client->greet('ieliwb');
        var_dump($result);
        echo "The answer isresult";
}
catch (SoapFault $f){
        echo "Error Message: {$f->getMessage()}";
}
?>

Create Webservice

1. Create wsdl

  • Non-standard webservice may only be accessible by PHP
  • For standard webservice, you must use wsdl (webservice description language, which is to use XML syntax standards to describe your service content. This is how I understand it)

Here I only introduce standard webservice. So how to create wsdl? This is indeed not easy for PHP. Some people say that it is very convenient to create with zend studio. This is one method. But for those who don't like to use zend studio, they may find it too difficult to create a webservice and install zend studio. I just, hehe.

Here I will introduce a simple method. Go to the Internet to download the SoapDiscovery.class.php class. There is a public method in it: getWSDL. The end of this method is return. Then, you can modify this method. This is what I do. of:

//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>'));

Now there is a class to generate wsdl, SoapDiscovery.class.php.

I only need to prepare a class or function that provides services to create wsdl. For example, I have a class: person, and the file name is: person.class.php★. There are two methods in it, one is say and the other is run. Very simple.

<?php
	class person
    {
        public function say()
        {
            return("i'm speaking.");
        }
        public function run()
        {
            return("i'm running,don't disturb me please.");
        }
    }
?>

There are two classes here: SoapDiscovery.class.php and person.class.php.

Start the formal generation of wsdl: create the file server.php. Copy the following content into it and run it to generate a person.wsdl file

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

2. Create webservice server program

Clear the contents of the server.php file and copy the following code into it:

<?php
    include("person.class.php");
    $objSoapServer = new SoapServer("person.wsdl");//person.wsdl是刚创建的wsdl文件
    //$objSoapServer = new SoapServer("server.php?wsdl");//这样也行
    $objSoapServer->setClass("person");//注册person类的所有方法
    $objSoapServer->handle();//处理请求
?>

3. Create a webservice client program to test whether the webservice is valid. The file name is: client.php

<?php
    $client = new SoapClient("person.wsdl");
    //$client = new SoapClient("server.php?wsdl");//这样也行
    echo($client->say());
    echo "<br />";
    echo($client->run());
    echo "<br />";
?>

OK, it’s over. If you want to use .NET, you just need to provide a URL to it.

How to get the URL: You can first search for

in the person.wsdl file. The URL here (the specific URL is based on your directory OK) is what you want to provide to .NET developers. But don’t be too happy too early. You need to add: “?wsdl” after it, http://xxxxxxxxxxxxxxxxxxxx/server.php?wsdl. This is the right way. If you don’t believe me, you can copy the url to the address bar of the browser and take a look. .

After a .NET developer obtains the URL you gave him, he can add a service reference or web reference to his project, and then complete the relevant operations according to the prompts. This is very convenient for developers using .NET Simple.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752376.htmlTechArticleWSDL WSDL (Web Services Description Language) is an XML-based language used to describe Web Services and how to access them. This kind of document can...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use