Example of Calling a Web Service based on wsdl through PHP

There are two ways to call Web Service with PHP :

i) Calling Web Service with SOAP Client in PHP:
PHP comes up with an in built class that is SOAP Client. You can use this like below code
You just need to create an object of SOAP Client Class and it requires a wsdl URL as an arguement.
Below code snippet gives better explanation

<?php
$client = new SoapClient("http://site.info/index.php?/wpws/?wsdl");
echo "<pre />";
print_r($client->getPosts(101));
echo "</pre>";
?>

This calling is based on wsdl file. Here getPost is a method that is created on remote server that is being consumed by all clients.

ii) We have external library available here(http://sourceforge.net/projects/nusoap/).

<?php

// Use the NuSOAP php library
require_once('lib/nusoap.php');

// Set parameters
$userName = 'usertest';
$password = 'testing';

// Build SOAP message. The objective of below code is to pass username and password into header into webservice for Login. Then it calls the testLogin
$body = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<UserInfo xmlns="http://yournameserverurl">
<UserName>'.$userName.'</UserName>
<Password>'.$password.'</Password>
</UserInfo>
</soap:Header>
<soap:Body>
<testLogin xmlns="http://yournameserverurl" />
</soap:Body>
</soap:Envelope>';

// Set up web service path and SOAP action variable
$serverpath = "http://yourserverpath";
$soapaction = "http://abc.com/testLogin";

// Create new SOAP client object instance
$client = new nusoap_client($serverpath);

$results = $client->send($body, $soapaction,'');

// Display output
echo "<h2>Request</h2>";
echo "<pre>" . htmlspecialchars($client->request,ENT_QUOTES) . "</pre>";
echo "<h2>Response</h2>";
echo "<pre>" . htmlspecialchars($client->response, ENT_QUOTES) . "</pre>";

// Dispose SOAP client
unset($client);

?>

Related posts:

The following two tabs change content below.

Chandra Shekhar

GCP Architect
Chandra Shekhar Pandey is Google certified Cloud engineer, I am Magento2 Trained developer. Having huge experience in designing cloud solution. I have around 12 years of experience with world enterprise IT companies and fortune 500 clients. During my architecture design I am always caring about high availability, fast performance and resilient system. From the programmer background I have huge experience in LAMP stack as well. Throughout my carrier I have worked on Retail, E-Learning, Video... Read More about Chandra Shekhar

Latest posts by Chandra Shekhar (see all)