使用Guzzle消耗SOAP [英] Using Guzzle to consume SOAP

查看:306
本文介绍了使用Guzzle消耗SOAP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢刚刚发现的Guzzle框架.我正在使用它来使用不同的响应结构在多个API上聚合数据.可以使用JSON和XML找到它,但是我需要使用的服务之一就是使用SOAP.有使用Guzzle消费SOAP服务的内置方法吗?

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?

推荐答案

您可以让Guzzle发送SOAP请求. 请注意,SOAP始终具有信封,标题和正文.

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>

我要做的第一件事是使用SimpleXML构建xml正文:

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);

然后,我们用SOAP信封,标头和正文包装xml正文.

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

然后我们需要在api文档中找出端点.

We then need to find out what our endpoint is in the api docs.

然后我们在Guzzle中构建客户端:

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 !!!';
}

这篇关于使用Guzzle消耗SOAP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆