问题描述
我正在尝试向希望CDATA作为请求一部分的服务发出SOAP请求。我成功使用Insomnia和以下两项作品之一成功进行了通话:
<ExecuteRequest xmlns="<url>">
<TAG1>
<![CDATA[
<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG3>
<TAG5>TEXT3</TAG5>
</TAG2>
]]>
</TAG1>
</ExecuteRequest>
OR
<ExecuteRequest xmlns="<url>">
<TAG1>
<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
</TAG2>
</TAG1>
</ExecuteRequest>
但是我在翻译以上内容以配合PHP soapclient时遇到了麻烦。例如,使用以下命令:
$soapclient = new SoapClient('url?wsdl',array('trace' => 1));
$xmlWriter = new \XMLWriter();
$xmlWriter->openMemory();
$xmlWriter->startElement('TAG1');
$xmlWriter->startElement('TAG2');
$xmlWriter->writeElement('TAG3','TEXT1');
$xmlWriter->writeElement('TAG4','TEXT2');
$xmlWriter->writeElement('TAG5','TEXT3');
$xmlWriter->endElement();
$xmlWriter->endElement();
$myXml = $xmlWriter->outputMemory(true);
$params = array(
new \SoapParam(new \SoapVar($myXml,XSD_ANYXML),'param')
);
$response = $soapclient->__soapCall('ExecuteRequest',$params);
$lastrequest = $soapclient->__getLastRequest();
$ soapclient-> __ getLastRequest()给我这个输出,这显然不是我想要的,没有CDATA:
<TAG1>
<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
</TAG2>
</TAG1>
如果不是在xmlwriter中,我使用它来手动编写CDATA:
$xmlWriter->writeCdata('<TAG2>
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
</TAG2>');
然后出于某种奇怪的原因,$ soapclient-> __ getLastRequest()返回已注释掉的CDATA部分,但我不知道为什么会这样:
<TAG1>
<!--[CDATA[<TAG2-->
<TAG3>TEXT1</TAG3>
<TAG4>TEXT2</TAG4>
<TAG5>TEXT3</TAG5>
""]]>"
</TAG1>
请注意,TAG2的结束标签也将丢失。
编辑
如果我不使用xml writter,则会发生与CDATA被注释掉相同的问题。
$wholeTag = new \SoapVar("<TAG1><![CDATA[{$text}]]></TAG1>",XSD_ANYXML);
$params = [
'param' => $wholeTag,];
有什么想法吗?我很可能会以错误的方式进行处理,因此我愿意接受任何建议。
解决方法
在浪费了几个小时之后,我最终完全使用了soapclient丢弃并用Guzzle解决了。
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
$xml = new \SimpleXMLElement("<put the whole xml body here,using the Webservice's SOAP 1.1 sample as a reference>");
$xmlstring = $xml->asXML();
$client = new Client();
$url = "< the **full** webservice url (used the Webservice's SOAP 1.1 sample as reference)>";
$action = "action url (used the Webservice's SOAP 1.1 sample as reference)";
try {
$response = $client->post($url,['headers' =>
['SOAPAction' => $action,'Content-Type' => 'text/xml; charset=utf-8','Host' => "<host url (used the Webservice's SOAP 1.1 sample as reference)>"
],'body' => $xmlstring
]);
}
catch (GuzzleException $e)
{
return [ 'status' => $e->getResponse()->getStatusCode(),'message' => $e->getResponse()->getReasonPhrase()];
}
if ($response->getStatusCode() === 200) {
// Success!
return $response->getBody();
}