Calling a SOAP web service from PHP
The SOAP binding is RPC/encoded, and the WSDL is not published.
Using the PHP SoapClient:
define('NEWLINE', "<br />\n");
// SOAP client
$options = array
(
'location' => 'https://example.com:1234/sample/service',
'uri' => 'http://example.com/sample/namespace/data',
'style' => SOAP_RPC,
'use' => SOAP_ENCODED,
'trace' => true // in conjunction with $soapClient->__getLastRequest() below
);
$soapClient = new SoapClient(null, $options);
// SOAP header
$nsHeader = 'http://example.com/sample/namespace/security';
$elementName = 'Security';
$usernameToken->Username = new SoapVar('user9', XSD_STRING, null, null, null, $nsHeader);
$usernameToken->Password = new SoapVar('pass1234', XSD_STRING, null, null, null, $nsHeader);
$content->UsernameToken = new SoapVar($usernameToken, SOAP_ENC_OBJECT, null, null, null, $nsHeader);
$soapHeader = new SoapHeader($nsHeader, $elementName, $content);
$soapHeaders[] = $soapHeader;
$soapClient->__setSoapHeaders($soapHeaders);
// SOAP call
$method = 'getData';
$parameters = array
(
new SoapParam('abcdef', 'param1'),
new SoapParam(12345, 'param2')
);
$success = true;
try
{
$result = $soapClient->__soapCall($method, $parameters);
}
catch (SoapFault $fault)
{
echo "Fault code: {$fault->faultcode}" . NEWLINE;
echo "Fault string: {$fault->faultstring}" . NEWLINE;
$success = false;
}
echo $soapClient->__getLastRequest(); // output the request XML
if ($success)
{
echo "<pre>\n";
print_r($result);
echo "</pre>\n";
}
if ($soapClient != null)
{
$soapClient = null;
}
Using curl:
define('NEWLINE', "<br />\n");
$ch = curl_init();
$data = '<soapenv:Envelope xmlns:ns2="http://example.com/sample/namespace/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://example.com/sample/namespace/data">
<soapenv:Header>
<ns2:Security>
<ns2:UsernameToken>
<ns2:Username>user9</ns2:Username>
<ns2:Password>pass1234</ns2:Password>
</ns2:UsernameToken>
</ns2:Security>
</soapenv:Header>
<soapenv:Body>
<ns1:getData soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<param1 xsi:type="xsd:string">abcdef</param1>
<param2 xsi:type="xsd:integer">12345</param2>
</ns1:getData>
</soapenv:Body>
</soapenv:Envelope>';
$fh = fopen('soap_response.txt', 'w');
curl_setopt($ch, CURLOPT_URL, 'https://example.com:1234/sample/service');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLKEY, 'sample.pem');
curl_setopt($ch, CURLOPT_FILE, $fh);
if (curl_exec($ch) === false)
{
echo "Curl error: " . curl_error($ch) . NEWLINE;
}
else
{
echo "Operation completed successfully" . NEWLINE;
}
curl_close($ch);
fclose($fh);
Comments: