Yii2 如何处理来自 api 回调的 XML 响应



我期待来自回调URL的xml响应。回调设置为类似。

http:://example.com/index/controllerExample/ActionResponseView

来自回调 URL 的示例 XML

<?xml version="1.0" encoding="UTF-8"?>
  <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="tns:ns">
  <SOAP-ENV:Body>
  <ns1:ResultMsg>
  <PHONE_NUMBER ns1:type="xsd:string">XXXXXXXXXX</PHONE_NUMBER>
  </ns1:ResultMsg>
  </SOAP-ENV:Body>
  </SOAP-ENV:Envelope>

使用 yii2 标准在哪里初始化 DOMDocument。它应该进入控制器示例还是直接在操作响应视图中?

$xmlFromServer = file_get_contents('php://input');
$doc = new DOMDocument();
$doc->loadXML($xmlFromServer);
$res = $doc->getElementsByTagName("PHONE_NUMBER");
$PHONE_NUMBER = $res->item(0)->nodeValue;

您可以定义自定义响应格式并在控制器中编写简单的return ['PHONE_NUMBER' => 'XXXXXXXXXX'];

在配置中写入:

'components' => [
    'response' => [
        'class' => 'yiiwebResponse', //It may be your custom response
        'format' => 'MyApi',
        'formatters' => [
            'MyApi' => 'appapiMyApiFormatter'
        ]
    ],
];

格式化程序应扩展XmlResponseFormatter并更改format方法。

这样,在

控制器中,您只关心正确的数据,在格式化程序中,您只关心响应格式。

最新更新