使用PHP 7将XML SOAP解析为对象JSON

时间:2017-05-28 10:45:57

标签: php json xml soap

我有以下问题,我需要从$ response = $ client - >转换SOAP响应。 __ getLastResponse();并转换为JSON对象。以下是使用上述方法在PHP中获得的响应的图像。

stdClass返回$ result:

stdClass Object ( [RealizarConsultaSQLResult] => AEC4 - AEC7 - )

响应SOAP:

<NewDataSet><Resultado> <CODTURMA>AEC4</CODTURMA><NOME>-</NOME></Resultado><Resultado><CODTURMA>AEC7</CODTURMA><NOME>-</NOME> 
</Resultado></NewDataSet>

观察:我的代码工作正常,只需要收到以下格式的答案:(预期输出):

{
  "NewDataSet": {
    "Resultado": [
      {
        "CODTURMA": "AEC4",
        "NOME": "-"
      },
      {
        "CODTURMA": "AEC7",
        "NOME": "-"
      }
    ]
  }
}

我的代码

   <?php
    require("wsdls.php");
    //Cabeçalho de autenticação básica no SOAP
    $soapParams = array('login' => $usuario,
                     'password' => base64_decode($pass),
               'authentication' => SOAP_AUTHENTICATION_BASIC,
                        'trace' => 1,
                   'exceptions' => 0
    );

    $client = new SoapClient($WsdlRMSQL, $soapParams); 
    $params = array('codSentenca' => 'TOTVS.MDA.402', 'codColigada'=>'1', 'codSistema'=>'S','parameters'=>'CODCOLIGADA=1;CODFILIAL=1;IDPERLET=2;IDHABILITACAOFILIAL=10');

    //Resultado do Webservice
    $result = $client->realizarConsultaSQL($params);

    //Resposta do SOAP
    $response = $client->__getLastResponse();
    //$xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
    //var_dump($response);
    print_r($response);


    ?>

Image form SOAP response

1 个答案:

答案 0 :(得分:0)

try{    
    $xml = $client->__getLastResponse();
    // SimpleXML seems to have problems with the colon ":" in the <xxx:yyy> response tags, so take them out

    $xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xml);
    $xml = simplexml_load_string($xml);
    $json = json_encode($xml);
    $responseArray = json_decode($json,true);

    // dd($responseArray['soapenvHeader']['headResponseHeader']['headStatusMessages']['headMessageDescription']);

    Log::info("bill payment response".json_encode($result));
    Log::info("bill payment response xml".$client->__getLastResponse());

    if(!empty($responseArray['soapenvBody'])):
        return redirect()->back()->with('status', $responseArray['soapenvHeader']['headResponseHeader']['headStatusMessages']['headMessageDescription']);
    else:
        return redirect()->back()->with('err', "We could not complete your request, please try again");
    endif;

} catch (\SoapFault $fault) {
    Log::info("bill payment error".json_encode($fault));
    return redirect()->back()->with('err', $fault->getMessage());
}