How to easily consume a web service from PHP
I've had great success with wsdl2php. It will automatically create wrapper classes for all objects and methods used in your web service.
Consuming web service (Soap) using php client
Try one of below solutions; You can do it in 3 ways:
1) Use PHP SoapClient()
function
<?php
$wsdl = "https://<your_web_service_url>?wsdl";
$client = new SoapClient($wsdl, array('trace'=>1)); // The trace param will show you errors stack
// web service input params
$request_param = array(
"param1" => $value1,
"param2" => $value2,
"param3" => $value3,
"param4" => $value4
);
try
{
$responce_param = $client->webservice_methode_name($request_param);
//$responce_param = $client->call("webservice_methode_name", $request_param); // Alternative way to call soap method
}
catch (Exception $e)
{
echo "<h2>Exception Error!</h2>";
echo $e->getMessage();
}
?>
2) NuSoap library to create instance of soap client. For NuSoap library check,
NuSoap Library and soap client Example.
<?php
require_once('lib/nusoap.php');
$wsdl = "http://<your_web_service_url>?wsdl";
$client = new nusoap_client($wsdl, 'wsdl');
// Input params
$username = "username";
$password = "pass";
// In this demo, we use json data , you can use any other data format for same
$json = '{"param1":"value1","param2":"value2"}';
$client->setCredentials($username, $password);
$error = $client->getError();
if ($error)
{
echo $error; die();
}
$action = "webservice_methode_name"; // webservice method name
$result = array();
if (isset($action))
{
$result['response'] = $client->call($action, $json);
}
echo "<h3>Output : </h3>";
echo $result['response'];
echo "<h2>Request</h2>";
echo "<pre>" . htmlspecialchars($client->request, ENT_QUOTES) . "</pre>";
echo "<h2>Response</h2>";
echo "<pre>" . htmlspecialchars($client->response, ENT_QUOTES) . "</pre>";
?>
3) Using curl you can call Soap webservice
<?php
$webservice_url = "https://<your_web_service_url>";
$request_param = array(
"param1" => $value1,
"param2" => $value2,
"param3" => $value3,
"param4" => $value4
);
$ch = curl_init($webservice_url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $request_param);
//curl_setopt ($ch, CURLOPT_TIMEOUT, 120);
// time allowed to connect to server
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,30);
// time allowed to process curl call
curl_setopt($ch,CURLOPT_TIMEOUT,120);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "<username>:<password>");
/* ** Alternative way to set username and password ** */
//$headers = array(
// 'Content-Type:application/xml',
// 'Authorization: Basic '. base64_encode("<username>:<password>")
//);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$data = curl_exec ($ch);
$result = $data;
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($ch),
htmlspecialchars(curl_error($ch)));
}
curl_close ($ch);
echo "Responce : ".$data;
?>
Right way to consume this SOAP service with PHP
Sometimes the SoapClient
is just a "broken tool". I would try to use curl or Guzzle as HTTP client and build the SOAP request manually. I have used SoapUI to generate a sample SOAP request according to the WSDL.
Example
<?php
// Change the url
$endpoint = 'http://172.20.2.18:1024/ADInterface/services/ModelADService';
$soapMethod = 'queryData';
// Basic Auth (optional)
$soapUser = ''.
$soapPassword = '';
// Created with SoapUI
$soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:adin="http://3e.pl/ADInterface">
<soapenv:Header/>
<soapenv:Body>
<adin:queryData>
<adin:ModelCRUDRequest>
<adin:ModelCRUD>
<adin:serviceType>?</adin:serviceType>
<adin:TableName>?</adin:TableName>
<adin:RecordID>?</adin:RecordID>
<adin:Filter>?</adin:Filter>
<adin:Action>?</adin:Action>
<!--Optional:-->
<adin:DataRow>
<!--Zero or more repetitions:-->
<adin:field type="?" column="?" lval="?" disp="?" edit="?" error="?" errorVal="?">
<adin:val>?</adin:val>
<!--Optional:-->
<adin:lookup>
<!--Zero or more repetitions:-->
<adin:lv val="?" key="?"/>
</adin:lookup>
</adin:field>
</adin:DataRow>
</adin:ModelCRUD>
<adin:ADLoginRequest>
<adin:user>?</adin:user>
<adin:pass>?</adin:pass>
<adin:lang>?</adin:lang>
<adin:ClientID>?</adin:ClientID>
<adin:RoleID>?</adin:RoleID>
<adin:OrgID>?</adin:OrgID>
<adin:WarehouseID>?</adin:WarehouseID>
<adin:stage>?</adin:stage>
</adin:ADLoginRequest>
</adin:ModelCRUDRequest>
</adin:queryData>
</soapenv:Body>
</soapenv:Envelope>';
$headers = array(
'Content-type: text/xml;charset="utf-8"',
'Accept: text/xml',
'Cache-Control: no-cache',
'Pragma: no-cache',
// Maybe change this url
'SOAPAction: ' . $endpoint . '/' . $soapMethod,
'Content-length: ' .strlen($soap),
);
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
// Basic Auth (optional)
curl_setopt($ch, CURLOPT_USERPWD, $soapUser. ':' .$soapPassword);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $soap);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Invoke request
$response = curl_exec($ch);
if($response === false) {
echo 'HTTP error: ' . curl_error($ch);
exit;
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$xml = trim(substr($response, $headerSize));
curl_close($ch);
// Convert response to DOM document
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml);
echo $dom->saveXML();
Call asp.net web service from PHP with multiple parameters
Try like this:
$client = new SoapClient("http://testurl/Test.asmx?WSDL");
$params->Param1 = 'Hello';
$params->Param2 = 'World!';
$result = $client->TestMethod($params)->TestMethodResult;
How to consume a webservice with PHP using WSDL mode
I finally got my answer... It was a difficult one and I'm not even sure how I spotted it but the problem was in the WSDL definition.
More specifically, the binding style was wrong (or at least not compatible with the client I was using).
The original one was document
and I needed it to be rpc
.
Once I made that little change everything worked as expected.
I'm leaving a reference to my code for someone else looking at it.
Edit: for the record, this site's example was the one that tipped me off :)
Consume a .Net web service using PHP
I think this should do the trick:
www.php.net/manual/en/soapclient.setsoapheaders.php
$ns = "http://tempuri.org/"
//Body of the Soap Header.
$headerbody = array('UserName' => $yourUsername,
'Password' => $yourPassword,
);
//Create Soap Header.
$header = new SOAPHeader($ns, 'AuthHeader', $headerbody);
//set the Headers of Soap Client.
$soap_client->__setSoapHeaders($header);
Call A C# Web Service From PHP Client
This is the right Answer I found it by myself and I like to share it for other developers
<?php
//Use C# Web Service:
$client2 = new SoapClient("http://www.emadbook.com/TestWebService/Convert.asmx?WSDL");
$params = new ArrayObject();
$params->Celsius = 37;
$result = $client2->CelsiusToFahrenheit($params)->CelsiusToFahrenheitResult;
echo $result;
?>
How to call soap web service from php
maybe try this ...
$responce_param = $client->GetCategories($request_param);
print_r($responce_param);
or even
$responce_param = $client->GetCategories($request_param);
$values = get_object_vars($responce_param);
$myresults = object_to_array($values);
print_r($myresults);
Related Topics
Install Imagick for PHP and Apache on Windows
Codeigniter - Best Place to Declare Global Variable
How to Create Codeigniter Batch Insert Array
Getting a Modified Preorder Tree Traversal Model (Nested Set) into a <Ul>
Regular Expression to Collect Everything After the Last /
How to Use Regexiterator in PHP
The Difference Between Unset and = Null
Token Must Be a Short-Lived Token and in a Reasonable Timeframe
How to Delete an Object's Property in PHP
Uncompress Gzip Compressed Http Response
Unexpected Character in Input: '\' (Ascii=92) State=1
Ssl Operation Failed with Code 1: Dh Key Too Small
Back to Previous Page with Header( "Location: " ); in PHP
Laravel 5.5 the Page Has Expired Due to Inactivity. Please Refresh and Try Again