我可以在发送之前预览PHP SOAP要发送的XML吗?

时间:2010-10-26 07:25:17

标签: php soap

根据标题,是否可以在尝试运行new SoapClient之前输出__soapCall()已创建的XML,以确保在将其实际发送到SOAP服务器之前是正确的?

3 个答案:

答案 0 :(得分:12)

您可以使用派生类并覆盖SoapClient类的__doRequest() method

<?php
//$clientClass = 'SoapClient';
$clientClass = 'DebugSoapClient';
$client = new $clientClass('http://www.webservicex.com/CurrencyConvertor.asmx?wsdl');
$client->sendRequest = false;
$client->printRequest = true;
$client->formatXML = true;

$res = $client->ConversionRate( array('FromCurrency'=>'USD', 'ToCurrency'=>'EUR') );
var_dump($res);

class DebugSoapClient extends SoapClient {
  public $sendRequest = true;
  public $printRequest = false;
  public $formatXML = false;

  public function __doRequest($request, $location, $action, $version, $one_way=0) {
    if ( $this->printRequest ) {
      if ( !$this->formatXML ) {
        $out = $request;
      }
      else {
        $doc = new DOMDocument;
        $doc->preserveWhiteSpace = false;
        $doc->loadxml($request);
        $doc->formatOutput = true;
        $out = $doc->savexml();
      }
      echo $out;
    }

    if ( $this->sendRequest ) {
      return parent::__doRequest($request, $location, $action, $version, $one_way);
    }
    else {
      return '';
    }
  }
}

打印

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.webserviceX.NET/">
  <SOAP-ENV:Body>
    <ns1:ConversionRate>
      <ns1:FromCurrency>USD</ns1:FromCurrency>
      <ns1:ToCurrency>EUR</ns1:ToCurrency>
    </ns1:ConversionRate>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
NULL

但是你必须稍微更改一下实际的代码,以便在可能的情况下尽量避免(即让工具完成工作)。

答案 1 :(得分:6)

不是之前,而是之后。参见

SoapClient::__getLastRequest - 返回上次SOAP请求中发送的XML。

只有在跟踪选项设置为SoapClient的情况下创建TRUE对象时,此方法才有效。

手册示例:

<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

答案 2 :(得分:0)

请注意,如果您可以控制SOAP服务器,则可以实际捕获发送到服务器的原始SOAP请求。为此,您需要扩展SOAP服务器。

示例代码:

class MySoapServer extends SoapServer 
{
    public function handle($request = null)
    {
      if (null === $request)    
      $request = file_get_contents('php://input');
      // Log the request or parse it...
    }
}