Using SOAP in PHP

Jul 30, 2016 pm 01:29 PM
gt lt nbsp quot soap

SOAP means "soap" in English. But this thing has influenced the Internet world to a great extent. After the concept of "Web services" was hyped in the past few years, SOAP is its achievement or "legacy", because SOAP ushered in the implementation of Web services.
SOAP = Simple Object Access Protocol, Simple Object Access Protocol. It is a lightweight, simple, XML-based protocol designed to exchange structured and solidified information on the WEB. SOAP can be used in conjunction with many existing Internet protocols and formats, including Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and Multipurpose Internet Mail Extensions (MIME). It also supports a wide range of applications from messaging systems to remote procedure calls (RPC).
Web services implemented through the SOAP protocol allow classes and functions written by programmers around the world to be gathered together to build a huge function library, which is language-independent. This depicts a brilliant development prospect for the software industry. As long as the network is connected, code-level logic sharing can be achieved. The past cross-process, cross-machine, and cross-network communication problems have all been solved, and http The protocol can pass through the firewall (in fact, firewalls generally do not block port 80 of the http protocol, otherwise no one will be able to access the Internet).
No wonder many people are very optimistic about this technology and call it "exciting".Web services are very simple to implement and can be easily published based on countless Web platforms on the Internet today. Simple is often the most beautiful, and Web services are a practical example.
In PHP, SOAP can be supported after the php_soap.dll extension is enabled in the php.ini file.
In the soap extension library, there are mainly three types of objects.
1. SoapServer
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.
    示例:
    文件 soapfunc.php:
        /* 几个供client端调用的函数 */
    function reverse($str)
    {
      $retval='';
      if(strlen($str)<1)
      {
        return new SoapFault('Client','','Invalid string');
      }
      for($i=1; $i<=strlen($str); $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;
    }
    ?>
    文件 soapclsoapserverient.php 内容:
          //先创建一个SoapServer对象实例,然后将我们要暴露的函数注册,
      //最后的handle()用来处理接受的soap请求
      include_once('soapfunc.php');
      error_reporting(7); //正式发布时,设为 0
      date_default_timezone_set('PRC'); //设置时区
      $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 内容:
          error_reporting(7);
      try
      {
        $client = new SoapClient(null, array('location'=>"http://localhost:8080/_myPHP5/soap/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;
      }
    ?>

PHP 中还实现了通过 WSDL 对 Web 服务的发布。

WSDL 是一种用于描述Web服务的语法规范,针对每个Web服务来说,它是一个说明文档,对web服务的位置,协议和接口进行详细的说明.由web服务的开发者提供。

WSDL文件包括5部分:types, Message,PortType,Binding和Service五部分.

1 Types definition: Type definition, independent of language. Corresponds to the definition of element information to be transmitted in the SOAP message
2 Message: Each web method corresponds to two message definitions in and out. The definition of message includes the header and body
3 PortType: Each web service corresponds to a PortType, which also contains the methods and operations published on it.
4 Bindings: Specifies the binding information of each operation (class and method) in each porttype, including The format of the input and output messages.
5 Service: The port information bound to each web service

In addition to publishing according to the aforementioned example, Web services can also be published through WSDL documents.

Example:

Class to publish, file myservice.php:
class service
{
public function HelloWorld()
{
return "Hello";
}
public function Add($a, $b)
{
return $a+$b;
}
}

$server=new SoapServer('TestSoap.wsdl',array('soap_version' => SOAP_1_2));
$server->setClass( "service");
$server->handle();
?>

WSDL description document, file TestSoap.wsdl:

targetNamespace="urn:TestSoap"
xmlns:typens="urn:TestSoap"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns :soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:wsdl="http:// schemas.xmlsoap.org/wsdl/"
xmlns="http://schemas.xmlsoap.org/wsdl/">












< /message>














































Calling code, file Client.php:

error_reporting(7);

$client = new SoapClient("http://localhost:8080/_myPHP5/soap/Wsdl/TestSoap.wsdl");
echo $client->HelloWorld() ;
echo("
");
echo $client->Add(10, 20);
?>

However, writing WSDL documents is a very troublesome thing, boring and error-prone . Many people think that this stuff was not written by humans, but if there are good software tools, then this stuff does not need to be written by humans. Zend's ZED 5.0 ​​series and Zend Studio for eclipse 6.0 originally supported WDSL visual editing and class publishing (intelligent generation according to a class file), but after Zend studio 7.0, this feature has been weakened. However, Zend studio 7.x, which is built on Eclipse, still has a WSDL visual editor, and its functions are sufficient. The generated WSDL The file has minor changes from before. Programmers must be familiar with the tags and elements in WSDL documents.

Appendix: Some errors about PHP soap development

1. When developing, be sure to turn off the cache of php soap, both the server and the client need it, otherwise it will report:

Fatal error: Uncaught SoapFault exception: [Client] Function ("test") is not a valid method for this service in ……clien.php:5 ​​Stack trace:
#0 [internal function]: SoapClient->__call('test', Array)
#1 D:xampphtdocsclien .php(5): SoapClient->test()
#2 {main}

Close method:
ini_set("soap.wsdl_cache_enabled", "0");

You can pass something like $client->__getFunctions( ) and other methods to view some information about Soap.


2. If an error of not recognizing XML is reported during debugging, please ensure that there are no spaces and other irrelevant information in the code, such as the BOM header of Utf-8 encoded files.

Author: Zhang Qing (Network) Xi'an PHP Education and Training Center 2010-7-11
From "Network Vision": http://blog.why100000.com
Author Weibo: http://t.qq.com/ zhangking
"One Hundred Thousand Whys" computer learning website: http://www.why100000.com


The above has introduced the use of SOAP in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

See all articles