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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor