如何将Magento2 SOAP API响应从Object更改为XML

时间:2017-07-27 08:11:06

标签: php api soap magento2

我创建了一个自定义Magento2 Soap API来从第三方服务器获取数据并将其保存到Magento DB中。 数据处理一切正常。现在,当我打印结果时,它是一个Object形式,但我只需要XML格式。 这是我用来发出请求的代码:

 $wsdlurl = 'MagentoStore/soap?wsdl&services=CustomDataApiManagementV1';
 $token = 'XXXXXXXXXXXX';
    $opts = ['http' => ['header' => "Authorization: Bearer " . $token]];
    $context = stream_context_create($opts);
    $addArgs = array('xmldata'=> 'testData');

    try{
        $soapClient = new SoapClient($wsdlUrl);
        $soapClient->setSoapVersion(SOAP_1_2);
        $soapClient->setStreamContext($context);
        $soapResponse = $soapClient
                     ->CustomDataApiManagementV1ProcessData($addArgs);
        print_r($soapResponse);
    }catch(Exception $e){
        echo 'error';
    }
  
    

此print_r($ soapResponse)显示结果如下:

  

stdClass对象([结果] =>成功)

我只需要XML格式的结果。

如果有人已经处理过,请告诉我。

1 个答案:

答案 0 :(得分:0)

尝试以下代码

$soapResponse = array_flip((array) $soapResponse);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($soapResponse, array ($xml, 'addChild'));
print $xml->asXML();

您的结果将如下所示

<root><result>Success</result></root>

来自How to convert array to SimpleXML

的来源