How to return a List of Objects from SOAP Web Service using PHP

Here in this tutorial I am going to show you how you can return a list of objects from SOAP web service using PHP programming language. SOAP is an acronym and stands for Simple Object Access Protocol. SOAP web service supports only XML format data type. SOAP itself is a messaging protocol that defines the structured information for exchanging in the implementation of the web service.

In my other example I had shown how to create SOAP service and how to consume using client script in PHP, but here I am going to show you how to return a list from SOAP service. The list may be a user list, an employee list, etc which you may want to return from a server.

In this example I am going to use contract first approach to build the web service. In contract first approach you need to first define the XSD and WSDL files for your SOAP service then you are going to implement the service. In contract last approach you generally implement your service then you are going to create the XSD and WSDL files.

Prerequisites

Apache HTTP Server 2.4, PHP 7.4.3

PHP SOAP Configuration

Project Directory

It’s assumed that you have setup Apache and PHP in your system.

Now I will create a project root directory called php-soap-service-list-objects under the Apache server’s htdocs folder.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

XSD and WSDL File

The WSDL (Web Service Definition Language) file defines the contract between client and server and it is both platform and language independent.

The following WSDL file contains the important semantics, such as, request, response, operation, port.

The XSD and WSDL information are kept into the file user.wsdl.

<?xml version="1.0" encoding="UTF-8"?>
<!-- WSDL File for web service User -->
<definitions 
	xmlns="http://schemas.xmlsoap.org/wsdl/" 
	xmlns:ns1="rm:type"
	xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
	xmlns:tns="rm:soap"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
	targetNamespace="rm:soap"
	name="User">
    <types>
	  <schema targetNamespace="rm:type" 
			xmlns="http://www.w3.org/2001/XMLSchema" 
			xmlns:soap11-enc="http://schemas.xmlsoap.org/soap/encoding/" 
			xmlns:tns="rm:type" 
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

			<!-- Data types used for web service parameters. -->			
			<complexType name="UserListRec">
				<sequence>
					<element name="User" type="ns1:UserType" minOccurs="0" maxOccurs="unbounded"/>
				</sequence>
			</complexType>
			 
			<complexType name="UserType">
				<sequence>
					<element name="LastName" type="xsd:string" />
					<element name="FirstName" type="xsd:string" />
					<element name="Email" type="xsd:string" />
				</sequence>
			</complexType>
			
			<complexType name="Void">
				<sequence>
				</sequence>
			</complexType>
        </schema>
     </types>

	<message name="UserEndpoint_getUserList">
        <part name="input" type="ns1:Void"/>
    </message>
	
    <!-- Output message(parameter) -->
    <message name="UserEndpoint_getUserListResponse">
        <part name="Users" type="ns1:UserListRec"/>
    </message>

    <!-- Description of various methods/operations of the web service -->
    <portType name="UserEndpoint">
        <operation name="getUserList" parameterOrder="inPara">
			<input message="tns:UserEndpoint_getUserList"/>
            <output message="tns:UserEndpoint_getUserListResponse"/>
        </operation>
    </portType>

    <!-- Description of various methods/operations of the web service -->
    <binding name="UserEndpointBinding" type="tns:UserEndpoint">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="getUserList">
            <soap:operation/>
			<input>
                <soap:body use="literal" namespace="rm:soap"/>
            </input>
            <output>
                <soap:body use="literal" namespace="rm:soap"/>
            </output>
        </operation>
    </binding>
	
    <service name="User">
       <port name="UserEndpointPort" binding="tns:UserEndpointBinding">
           <soap:address location="http://localhost/php-soap-service-list-objects/user_ws.php"/>
       </port>
   </service>
</definitions>

In the above WSDL file I have defined the XSD part using the tag <types/>. The <message/> tag is used to define the request and response part of the service. The <portType/> is bound to the operation part in file. Finally the endpoint of the service is specified in the address location.

The above definition, if you notice, has the UserType which is being called from UserListRec that specifies the list of records or an array of objects from 0 to unlimited.

return a list of objects from soap web service using php

SOAP Service

Now I am going to implement the server part. The server code is written into a file user_ws.php.

<?php

function getUserList() {
	
	/*The following data will actually be fetched from database or any external service*/
	$user1 = new StdClass();
	$user1->LastName = 'Tester';
	$user1->FirstName = 'Jane';
	$user1->Email = 'jtester@testco.com';
	
	$user2 = new StdClass();
	$user2->LastName = 'Tester 2';
	$user2->FirstName = 'Jhon';
	$user2->Email = 'jtester2@testco.com';
	
	$users = array();
	$users[0] = $user1;
	$users[1] = $user2;
	
	$Users = new StdClass();
	$Users->User = $users;
	
	return $Users;
}

// Disable WSDL cache during development.
ini_set("soap.wsdl_cache_enabled", "0"); 

// Create SOAP server object to serve the web service.
$server = new SoapServer("user.wsdl");

// Add the web service methods to the server to handle them.
$server->addFunction("getUserList");

$server->handle();

As you see in the above code I have defined a method or function that will return a list of users. The data should actually be come from a database or external service or some persistent storage but for the sake of an example, I am returning sample data.

Next I have created SoapServer instance and adding the function that returns a list of users.

SOAP Client

The client PHP file (user_client.php) actually consume the SOAP service and show the result.

<?php

   //http://localhost/php-soap-service-list-objects/user_client.php

    echo "<html>";
    echo "<head>";
    echo "<title>User Web Application</title>";
    echo "</head>";
    echo "<body>";

    // Check if SOAP module is enabled with PHP server.
    $soap_enabled = class_exists("SOAPClient"); 
    if ($soap_enabled = 0) {
        die("SOAP Module not found with PHP server.");
    }

    // Create the SOAP client object for the web service.
    // Disable wsdl caching during development.
    ini_set("soap.wsdl_cache_enabled", "0");   

    try {
		// Setup web service URL.
		$ws_url = "http://localhost/php-soap-service-list-objects/user_ws.php";
		
		// Setup WSDL file.
		$wsdl_file = "user.wsdl";
		
		// Setup options for SOAP Client.
		$options = array('location' => $ws_url, 'soap_version'   => SOAP_1_1);
		
		// Create SOAP Client object for invoking web service methods.
		$soapclient = new SoapClient($wsdl_file, $options);

		// Call the web service method.
		$response = $soapclient->getUserList();
		
		//echo var_dump($response);
		//echo var_dump($response->User);
		
		$users = $response->User;
		echo "<br>Number of Users: " . sizeof($users);
		
		echo "<br>";
        echo "<h1>User Information</h1>";
        echo "<table border=1>";
		for ($i = 0; $i < sizeof($users); ++$i) {
			$user = $users[$i];
			echo "<tr>";
			echo "<td>" . $user->LastName . "</td>";
			echo "<td>" . $user->FirstName . "</td>";
			echo "<td>" . $user->Email . "</td>";
			echo "</tr>";
		}
		echo "</table>";
    } catch (Exception $e) {
        echo "<br>Error! ". $e;
        echo $e->getMessage ();
        echo "<br>Last request: ". $soapclient->__getLastRequest();
        echo "<br>Last response: ". $soapclient->__getLastResponse();
    }

    echo "</body>";
    echo "</html>";

I have disabled the cache otherwise you may not get the latest data from the service. You can hit the URL http://localhost/php-soap-service-list-objects/user_client.php in the browser to get the result. You can also use SOAP UI tool to test the service.

Testing the SOAP Service

Make sure your Apache HTTP Server is up and running and your is inside the htdocs folder.

From Browser

Now you should be able to access the URL http://localhost/php-soap-service-list-objects/user_client.php in the browser and you will get the following result:

return a list of objects from soap web service using php

From SOAP UI

  • Open SOAP UI tool
  • Click on SOAP as shown below in the image
return a list of objects from soap web service using php
  • Browse and select your WSDL file as shown below and click OK
return a list of objects from soap web service using php
  • Now your project will be created on left side
  • Do double-click on the Request 1
return a list of objects from soap web service using php
  • Click on the highlighted item – green play button. You will get the result on the right side pane.
return a list of objects from soap web service using php

That’s all about how to create SOAP service that returns a list using PHP.

Source Code

Download

Leave a Reply

Your email address will not be published.