search
HomeBackend DevelopmentPHP Tutorialwebservice——nusoap detailed explanation

PHP SOAP Server

It is very easy to set up a SOAP server with PHP and NuSoap. Basically, you just write the functions you want to expose to your Web services and register them with NuSoap. OK, there are two more steps required to complete the establishment of the PHP SOAP server. First, you have to create an instance of the NuSoap object in your PHP code, and then use the HTTP POST method to pass the original data to NuSoap for processing. The use of NuSOAP is relatively simple, and the most commonly used classes are soap_server and soapclient. ,

Among them soap_server is used to create Webservice services, and class soapclient is used to call Webservice

. The definitions of these two classes are in lib/nusoap.php, so we need to reference this when creating or calling the Webservice interface program File. NuSoap is a WebService programming tool in the PHP environment, used to create or call WebService. It is an open source software, which is a series of PHP classes written entirely in PHP language that sends and receives SOAP messages through HTTP. It is developed by NuSphere Corporation (http://dietrich.ganx4.com/nusoap/). One advantage of NuSOAP is that it does not require extension library support. This feature allows NuSoap to be used in all PHP environments and is not affected by server security settings. ​

1.

First, go to http://sourceforge.net/projects/nusoap/download nusoap.zip. 2.Server: Create the
nusoapService.php
file.

[php] view plaincopy

  1. require_once ("lib/nusoap.php");
  2. $server = new soap_server () ;
  3. //Avoid garbled characters
  4. $server->soap_defencoding = 'UTF-8';
  5. $server-> ;decode_utf8 = false;
  6. $server->xml_encoding = 'UTF-8'; ->configureWSDL (
  7. 'test'
  8. ); //Open wsdl support /*
  9. Register programs that need to be accessed by the client
  10. Type corresponding value: bool->" xsd:boolean" string->"xsd:string"
  11. int->"xsd:int" float->"xsd:float"
  12. */
  13. $server->register (
  14. 'GetTestStr'
  15. , //Method name array (
  16. "name"
  17. => "xsd:string" ), // Parameters, the default is "xsd:string" array (
  18. "return"
  19. => "xsd:string " ) ); //Return value, default is "xsd:string" //isset Check whether the variable is set
  20. $HTTP_RA W_POST_DATA = isset (
  21. $HTTP_RAW_POST_DATA
  22. ) ? $HTTP_RAW_POST_DATA : ''; //service Process the data input by the client
  23. $server- >service (
  24. $HTTP_RAW_POST_DATA
  25. ); /**
  26. * Method for calling
  27. * @param $name
  28. */
  29. functionGetTestStr(
  30. $name
  31. ) { Resurn "Hello, {$ name}!"
  32. ;
  33. } ? & Gt;
  34. 3.
Client :Create the
nusoapClient.php
file.

[php] view plaincopy

  1. require_once ("lib/nusoap.php");
  2. /*
  3. Call WebService through WSDL
  4. Parameter 1 The address of the WSDL file (the wsdl after the question mark cannot be capitalized)
  5. Parameter 2 Specifies whether to use WSDL
  6. $client = new soapclient('http ://localhost /nusoapService.php?wsdl',true);
  7. */
  8. $client = new soapclient ( 'http://localhost/nusoapService. php' ); ->decode_utf8 = false;
  9. $client->xml_encoding='UTF-8';
  10. $paras = array (
  11. 'name' => 'Bruce Lee');
  12. $result = $client->call (
  13. 'GetTestStr', $paras); //Check for errors and get the return value
  14. if (! $err =
  15. $client->getError ()) { echo" Return results: " , $result;
  16. } else {
  17. echo" Call error : ", $err;
  18. } ?>
  19. [php] view plaincopy
    1. require_once ("lib/nusoap.php");
    2. /*
    3. Call WebService through WSDL
    4. Parameter 1 The address of the WSDL file (wsdl after the question mark cannot be capitalized)
    5. Parameter 2 Specifies whether to use WSDL
    6. $client = new soap client('http://localhost /nusoapService.php?wsdl',true);
    7. */
    8. $client = new soapclient ( 'http://localhost/nusoapService. php?wsdl',true); $client->decode_utf8 = false;
    9. $ paras = array (
    10. 'name' => Omit the following parameters
    11. $client->call ('GetTestStr', $paras
    12. ); $document
    13. = $client- >document; echo $document; Note:
    14. Return result: Hello, { Bruce Lee } ! WSDLWSDL is an XML language used to describe Web Services. It is a machine-readable format that provides all the information necessary to access the service to the Web Service client. NuSOAP specifically provides a class to parse WDSL files and extract information from them. The soapclient object uses the wsdl class to make it easier for developers to call services. By creating the message with the help of WSDL information, the programmer only needs to know the name and parameters of the operation to call it.
    15. Using WSDL through NuSOAP provides the following advantages:
    16. All service metafiles, such as namespaces, endpoint URLs, parameter names, etc., can be obtained directly from the WSDL file, thus allowing client dynamics to adapt to server-side changes. Because this data is always available from the server, this data no longer needs to be hard-coded in user scripts. It allows us to use soap_proxy class. This class is derived from the soapclient class and adds methods corresponding to the operations detailed in the WDSL file. Now users can directly call these methods through it. The soapclient class contains a getProxy() method which returns an object of the soap_proxy class. The soap_proxy class is derived from the soapclient class, adds methods corresponding to the operations defined in the WSDL document, and allows the user to call an endpoint's remote method. This only applies if the soapclient object is initialized with a WDSL file. The advantage is ease of use for users, the disadvantage is performance - creating objects in PHP is time consuming - and does not serve a utilitarian purpose (and this functionality serves no utilitarian purpose).
    17. [php] view plaincopy
      1. require_once ("lib/nusoap.php");
      2. $client = new soapclient ( 'http://localhost/nusoapService.php?wsdl',true);
      3. $client->decode_utf8 = false; $client->
      4. //Generate proxy class
      5. $proxy = $client->getProxy();
      6. //Call remote function
      7. $sq
      8. = $proxy->GetTestStr('Bruce Lee'); ->getError()) {
      9. print_r($sq);
      10. } else { : $err"; }
      11. print 'REQUEST:<xmp>'.$p->request.'</xmp>'
      12. ; print 'RESPONSE: <xmp>'
      13. .
      14. str_replace('>
      15. ,
      16. ">n, $p
    18. -> response ).
    19. ' </xmp>'
    20. ;
    21. ?> lfile Click on the method name. In this way, by adding a few lines of code to the service, we provide a visual document for the service using NuSOAP. But that's not all we can do.
    22. We add some WSDL calls to the service by using NuSOAP. We can generate WSDL and some other documents for the service. In contrast, there is not much we can do in the client, at least in our simple example. The client shown below is no different from the client that does not use WSDL. The only difference is that parsing the soapclent class is done by providing the URL of the WSDL instead of the service endpoint as before. Solution to garbled code when NuSoap calls WebService: [php] view plaincopy$client
    23. ->soap_defencoding =
    24. 'utf-8'
    25. ; code_utf8 = false;


$client->xml_encoding =

'utf-8'; Otherwise, an error similar to the following will be reported when calling :

XML error parsing SOAP payload on line

Implement WebService, Do not enable the SOAP

extension of php,

The reason is that the SoapClient class of nusoap conflicts with the built-in SOAP class of php5.

webservice——nusoap detailed explanationSolution

1. Modify php.ini not to load the built-in soap extension of php5 (php_soap.dll under windows).

2. Some people also renamed the SoapClient class of nusoap.

Identity authentication
  1. [php] view plaincopy
    1. header('content-type: text/xml; charset=UTF-8');  
    2. require_once('nusoap.php');  
    3. $params = array('AuthenticationHeader' => array(  
    4.     'Content-Type' => 'text/xml; charset=UTF-8',  
    5.     'SOAPAction' => 'YourFunstion',  
    6. )  
    7. );  
    8. $client = new nusoap_client('http://www.yourdomain.com/service.asmx?wsdl', true, '''''''');  
    9. $client->setHeaders('    
    10. "http://tempuri.org/webservice">  
  2.   username   
  3.   password     
  4.    
  5. ');  
  6. $err = $client->getError();  
  7. if ($err) {  
  8.     echo '

    Constructor error

    '
     . $err . '';  
  9. }  
  10. $result = $client->call('YourFunction'$params'''', false, true);  
  11. if ($client->fault) {  
  12.     echo '

    Fault

    '
    ;  
  13.     print_r($result);  
  14.     echo '';  
  15. else {  
  16.     $err = $client->getError();  
  17.     if ($err) {  
  18.         echo '

    Error

    '
     . $err . '';  
  19.     } else {  
  20.         echo '

    Result

    '
    ;  
  21. //print_r($result);  
  22.         echo '';  
  23.     }  
  24. }
  25. echo'

    Request

    '
    . htmlspecialchars($client->request, ENT_QUOT ES) .' pre>';
    ->response, ENT_QUOTES) .
  26. ''; ?> The above introduces the detailed explanation of webservice-nusoap, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool