I'm loving the Guzzle framework that I just discovered. I'm using it to aggregate data across multiple API's using different response structures. It's worked find with JSON and XML, but one the services i need to consume uses SOAP. Is there a built-in way to consume SOAP services with Guzzle?
You can get Guzzle to send SOAP requests. Note that SOAP always has an Envelope, Header and Body.
<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/">
<soapenv:Header/>
<soapenv:Body>
<NormalXmlGoesHere>
<Data>Test</Data>
</NormalXmlGoesHere>
</soapenv:Body>
The first thing I do is build the xml body with SimpleXML:
$xml = new SimpleXMLElement('<NormalXmlGoesHere xmlns="https://api.xyz.com/DataService/"></NormalXmlGoesHere>');
$xml->addChild('Data', 'Test');
// Removing xml declaration node
$customXML = new SimpleXMLElement($xml->asXML());
$dom = dom_import_simplexml($customXML);
$cleanXml = $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement);
We then wrap our xml body with the soap envelope, header and body.
$soapHeader = '<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:Body>';
$soapFooter = '</soapenv:Body></soapenv:Envelope>';
$xmlRequest = $soapheader . $cleanXml . $soapFooter; // Full SOAP Request
We then need to find out what our endpoint is in the api docs.
We then build the client in Guzzle:
$client = new Client([
'base_url' => 'https://api.xyz.com',
]);
try {
$response = $client->post(
'/DataServiceEndpoint.svc',
[
'body' => $xmlRequest,
'headers' => [
'Content-Type' => 'text/xml',
'SOAPAction' => 'https://api.xyz.com/DataService/PostData' // SOAP Method to post to
]
]
);
var_dump($response);
} catch (\Exception $e) {
echo 'Exception:' . $e->getMessage();
}
if ($response->getStatusCode() === 200) {
// Success!
$xmlResponse = simplexml_load_string($response->getBody()); // Convert response into object for easier parsing
} else {
echo 'Response Failure !!!';
}
IMHO Guzzle doesn't have full SOAP support and works only with HTTP requests. src/Guzzle/Http/ClientInterface.php Line:76
public function createRequest(
$method = RequestInterface::GET,
$uri = null,
$headers = null,
$body = null,
array $options = array()
);
Even if SOAP server is configured to negotiate on port 80 I think php SoapClient is more appropriate solution here as it supports WSDL
Old Topic, but as I was searching for the same answer, it seems async-soap-guzzle is doing the job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With