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

查看:43
本文介绍了使用 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天全站免登陆