使用Guzzle来使用SOAP

Lor*_*eck 20 soap guzzle

我喜欢我刚刚发现的Guzzle框架.我正在使用它来使用不同的响应结构在多个API之间聚合数据.它使用JSON和XML查找,但我需要使用的服务之一使用SOAP.有没有内置的方式来使用Guzzle的SOAP服务?

小智 9

您可以让Guzzle发送SOAP请求.请注意,SOAP始终具有Envelope,Header和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>
Run Code Online (Sandbox Code Playgroud)

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

$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);
Run Code Online (Sandbox Code Playgroud)

然后我们用肥皂信封,标题和正文包裹我们的xml主体.

$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
Run Code Online (Sandbox Code Playgroud)

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

然后我们在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 !!!';
}
Run Code Online (Sandbox Code Playgroud)


小智 5

恕我直言,Guzzle 没有完整的 SOAP 支持,仅适用于 HTTP 请求。src/Guzzle/Http/ClientInterface.php 行:76

public function createRequest(                                              
    $method = RequestInterface::GET,                                        
    $uri = null,                                                            
    $headers = null,                                                        
    $body = null,                                                           
    array $options = array()                                                
); 
Run Code Online (Sandbox Code Playgroud)

即使 SOAP 服务器配置为在端口 80 上进行协商,我认为 php SoapClient 是更合适的解决方案,因为它支持 WSDL