search
HomeBackend DevelopmentPHP TutorialSOAP webservice interface

SOAP webservice interface

Nov 24, 2016 pm 03:46 PM
soap

In PHP, SOAP can be supported after enabling the php_soap.dll extension in the php.ini file.
In the soap extension library, there are mainly three types of objects.
1. SoapServer
is used to define functions that can be called and return response data when creating PHP server-side pages. The syntax format for creating a SoapServer object is as follows:
  $soap = new SoapServer($wsdl, $array);
  Among them, $wsdl is the wsdl file used by shoep, wsdl is a standard format for describing Web Service, if $wsdl Set to null to not use wsdl mode. $array is the attribute information of SoapServer and is an array.
The addFunction method of the SoapServer object is used to declare which function can be called by the client. The syntax format is as follows:
$soap->addFunction($function_name);
Among them, $soap is a SoapServer object, and $function_name needs to be called. function name.
The handle method of the SoapServer object is used to process user input and call the corresponding function, and finally returns the processing result to the client. The syntax format is as follows:
$soap->handle([$soap_request]);
Among them, $soap is a SoapServer object, and $soap_request is an optional parameter used to represent the user's request information. If $soap_request is not specified, it means that the server will accept all requests from the user.
2. SoapCliet
is used to call the SoapServer page on the remote server and implements the call to the corresponding function. The syntax format for creating a SoapClient object is as follows:
$soap = new SoapClient($wsdl,$array);
Among them, the parameters $wsdl and $array are the same as SoapServer.
After creating the SoapClient object, calling the function in the server page is equivalent to calling the SoapClient method. The creation syntax is as follows:
$soap->user_function($params);
Among them, $soap is a SoapClient object and user_function is the server The function to be called, $params is the parameters to be passed into the function.
3. SoapFault
SoapFault is used to generate errors that may occur during soap access. The syntax format for creating a soapFault object is as follows:
$fault = new SoapFault($faultcode,$faultstring);
Among them, $faultcode is a user-defined error code, and $faultstring is a user-defined error message. The soapFault object is automatically generated when an error occurs on the server-side page, or when the user creates a SoapFault object. For errors that occur during Soap access, the client can obtain the corresponding error information by capturing the SoapFalut object.
After capturing the SoapFault object on the client, you can obtain the error code and error information through the following code:
$fault->faultcode;//Error code
$fault->faultstring;//Error information
Where, $fault Is the SoapFault object created earlier.
Both SoapServer and SoapClient receive two parameters. The second parameter is Option, which supports several options. Here we use:
uri: namespace. The client and server need to use the same namespace.
location: used by the client to specify the access address of the server program, which is the program address of the second code in this example.
trace: used by the client. When true, the content of the communication between the server and the client can be obtained for debugging.

Soapserver.php

Java code

//First create a SoapServer object instance, and then register the functions we want to expose,

//The last handle() is used to process the accepted soap Request

error_reporting(7); //When officially released, set to 0

date_default_timezone_set('PRC'); //Set the time zone

/* Several functions for client calls */

function reverse($ str)

{

$retval = '';

if (strlen($str)

return new SoapFault ('Client', '', 'Invalid string');

}

for ($i = 1; $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;  

}  

  

$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();  

?>  

 SoapClient.php

Java代码  

error_reporting(7);  

try {  

    $client = new SoapClient (null, array('location' => "http://www.yiigo.com/Soapserver.php", 'uri' => "http://test-uri"));  

  

    $str = "This string will be reversed";  

    $reversed = $client->reverse($str);  

    echo "if you reverse '$str', you will get '$reversed'";  

  

    $n1 = 20;  

    $n2 = 33;  

    $sum = $client->add2numbers($n1, $n2);  

    echo "
";  

    echo "if you try $n1 + $n2, you will get $sum";  

  

    echo "
";  

    echo "The remoye system time is: " . $client->gettime();  

} catch (SoapFault $fault) {  

    echo "Fault! code:" . $fault->faultcode . " string:" . $fault->faultstring;  

}  

?>  

if you reverse 'This string will be reversed', you will get 'desrever eb lliw gnirts sihT'
if you try 20 + 33, you will get 53
The remoye system time is: 2012-05-28 16:14:29

 

通过SoapHeader实现身份认证

Java代码  

class Server  

{  

    public function auth($a)  

    {  

        if ($a != '123456789') {  

            throw new SoapFault('Server', '用户身份认证信息错误');  

        }  

    }  

  

    public function say()  

    {  

        return 'Hi';  

    }  

}  

  

$srv = new SoapServer(null, array('uri' => 'http://localhost/namespace'));  

$srv->setClass('Server');  

$srv->handle();   

 客户端

Java代码  

$cli = new SoapClient(null,  

array('uri' => 'http://localhost/namespace/',

'location' => 'http://localhost/server.php',

'trace' => true) );

//auth is the function to be processed by the server 12345689 is the parameter

$h = new SoapHeader('http://localhost/namespace/',

'auth', '123456789', false, SOAP_ACTOR_NEXT);

$cli->__setSoapHeaders(array($h));

try {

echo $cli->say();

} catch (Exception $e) {

echo $e ->getMessage();

}

Pay attention to the fact that the server class in server.php has a method "auth", which just corresponds to the name of the header. The parameter $u of the auth method is the data of soapHeader, which soapServer receives This request will first call the auth method and pass "123456789" as a parameter to the method. When the mustUnderstand parameter is false, the say method will be called even if there is no auth method. However, if it is true, if the auth method does not exist, a Soapfault will be returned to inform that the header has not been processed. The actor parameter specifies which roles must process the header. I don't understand it very thoroughly here, so it's hard to say.

Java code

$file = $this->getSoapWSDL();

$client = new SoapClient($file);//url can be accessed through the browser and cannot be directly called to solve

$param = array( 'userID' => 'test', 'merchantID' => 'test');

$returnSt = $client->checkUser($param);

print_r($returnSt->checkUserResult);

public function getSoapWSDL()

{ //Regularly save the url file to the local

$file = Mage::getBaseDir() . DS . 'data' . DS . 'shengda' . DS . 'export. wsdl';

if (time() > filemtime($file) + 7 * 86400) {

$url = "http://jf.sdo.com/ExchangeScore/ExchangeService.asmx?WSDL";

include_once(BP . DS . "lib/Snoopy.class.php");

$snoopy = new Snoopy;

$snoopy->fetch($url); //Get all content

$snoop y-> read_timeout = 4;

$wsdl = $snoopy->results;

if ($snoopy->status == '200' && !$snoopy->timed_out) {

               if (!is_dir(dirname( $file))) {

                                                                                                                                                                                                                                                         

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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool