如何在php中解析soap xml响应并从字符串中获取信息

时间:2016-01-29 08:39:35

标签: php xml soap xml-parsing

我在从SOAP响应中提取信息时遇到了一些问题。 这是我得到的回应:

<?xml version="1.0" encoding="utf-8" ?> 
- <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <soap:Body>
- <GetInfoFromSendingResponse xmlns="http://test.test.com/">
  <GetInfoFromSendingResult>{"SendingID":"2468","Subject":"Test","ID":"2468","CampaignID":"890","ForwardAddress":"test@test.ro","SendingTime":"1/14/2016 8:00:00 AM","SendLeadsToEmail":"0","LanguageID":"6","LeadsTestMode":true,"WebversionLink":"","Language":"FR"}</GetInfoFromSendingResult> 
  </GetInfoFromSendingResponse>
  </soap:Body>
  </soap:Envelope>

我需要来自GetInfoFromSendingResult的信息并将其存储在变量中,以便我可以使用该信息。

示例:根据SOAP响应中提供的"Language"信息更改表单的语言。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

您可以使用SoapClient自带PHP 5.0+版本

$client = new SoapClient("http://test.test.com/?wsdl");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->GetInfoFromSendingResponse->GetInfoFromSendingResult;

然后您可能需要JSON解码才能获得一些特定值。

答案 1 :(得分:2)

另一种可能的解决方案是使用例如SimpleXML。您可以注册命名空间并使用xpath表达式:

$source = <<<SOURCE
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetInfoFromSendingResponse xmlns="http://test.test.com/">
            <GetInfoFromSendingResult>{"SendingID":"2468","Subject":"Test","ID":"2468","CampaignID":"890","ForwardAddress":"test@test.ro","SendingTime":"1/14/2016 8:00:00 AM","SendLeadsToEmail":"0","LanguageID":"6","LeadsTestMode":true,"WebversionLink":"","Language":"FR"}</GetInfoFromSendingResult>
        </GetInfoFromSendingResponse>
    </soap:Body>
</soap:Envelope>
SOURCE;

$xml = simplexml_load_string($source);
$xml->registerXPathNamespace('test', 'http://test.test.com/');
$elements = $xml->xpath('//soap:Envelope/soap:Body/test:GetInfoFromSendingResponse/test:GetInfoFromSendingResult');
$result = json_decode($elements[0], true);
print_r($result);

将导致:

Array
(
    [SendingID] => 2468
    [Subject] => Test
    [ID] => 2468
    [CampaignID] => 890
    [ForwardAddress] => test@test.ro
    [SendingTime] => 1/14/2016 8:00:00 AM
    [SendLeadsToEmail] => 0
    [LanguageID] => 6
    [LeadsTestMode] => 1
    [WebversionLink] => 
    [Language] => FR
)