Using Guzzle to consume SOAP

后端 未结 4 1955
夕颜
夕颜 2021-02-12 04:24

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

4条回答
  •  借酒劲吻你
    2021-02-12 05:09

    You can get Guzzle to send SOAP requests. Note that SOAP always has an Envelope, Header and Body.

    
        
        
            
                Test
            
        
    

    The first thing I do is build the xml body with SimpleXML:

    $xml = new SimpleXMLElement('');
    $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 = '';
    
    $soapFooter = '';
    
    $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 !!!';
    }
    

提交回复
热议问题