Get value from json response with SOAP request - php

After successfully getting a response from a SOAP request in JSON format, I cannot extract one property out of it.
Beholde the response I got from postman.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<AutenticacionResponse xmlns="https://figs.software/">
<AutenticacionResult xsi:type="xsd:string">{"CodRespuesta":"00","Respuesta":"bd026f95-61cf-4947-80df-bf519d544995","URL":null,"NCF":null}</AutenticacionResult>
</AutenticacionResponse>
</soap:Body>
</soap:Envelope>
My goad is to get the token of the Respuesta property.
I'm using curl of PHP to establish the connection:
I try to convert the response I got into an array like this:
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//soapBody ')[0];
$array = json_decode(json_encode((array)$body), TRUE);
echo $array['AutenticacionResponse']['AutenticacionResult'];
echo gettype($array);
I have this result:
{"CodRespuesta":"00","Respuesta":"d5810796-9563-4423-aff3-089d61e170b6","URL":null,"NCF":null}
array
How can I get the value of Respuesta ?

Without touching your code I get the answer by just doing
$json = json_decode($array['AutenticacionResponse']['AutenticacionResult'], true);
echo $json['Respuesta'];
And I would have done like this
<?php
$response = <<<XML
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<AutenticacionResponse xmlns="https://figs.software/">
<AutenticacionResult xsi:type="xsd:string">{"CodRespuesta":"00","Respuesta":"bd026f95-61cf-4947-80df-bf519d544995","URL":null,"NCF":null}</AutenticacionResult>
</AutenticacionResponse>
</soap:Body>
</soap:Envelope>
XML;
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$json = json_decode($xml->soapBody->AutenticacionResponse->AutenticacionResult, true);
echo $json['Respuesta'];

Related

Parse curl response from SOAP

I successfully get response from soap webservice using php curl. I would like to know how can I parse the curl response so that I got each value separately in other to save into database.
my codes:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://xxxxxx/WSAutorizaciones/WSAutorizacionLaboratorio.asmx?WSDL",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<AuthenticationHeader xmlns="https://arssenasa.gob.do/">
<Cedula>001-0946651-5</Cedula>
<Password>xxxxxxx</Password>
<Proveedo>12077</Proveedo>
</AuthenticationHeader>
</soap:Header>
<soap:Body>
<ConsultarAfiliado xmlns="https://arssenasa.gob.do/">
<TipoDocumento>2</TipoDocumento>
<NumDocumento>021827151</NumDocumento>
</ConsultarAfiliado>
</soap:Body>
</soap:Envelope>',
CURLOPT_HTTPHEADER => array("content-type: text/xml"),
))
;
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The result is displayed like this:
8013-0000655-6021827151MARGARET ADIRASANTANA LORENZO DE CABRAL08CONTRIBUTIVO22/11/197346FEMENINO08
the soap resonse is like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ConsultarAfiliadoResponse xmlns="https://arssenasa.gob.do/">
<ConsultarAfiliadoResult>
<Contrato>8</Contrato>
<Cedula>013-0000655-6</Cedula>
<Nss>021827151</Nss>
<Nombres>MARGARET ADIRA</Nombres>
<Apellidos>SANTANA LORENZO DE CABRAL</Apellidos>
<IdEstado>0</IdEstado>
<CodigoFamiliar>8</CodigoFamiliar>
<IdRegimen xsi:nil="true" />
<Regimen>CONTRIBUTIVO</Regimen>
<FechaNacimiento>22/11/1973</FechaNacimiento>
<Edad>46</Edad>
<Sexo>FEMENINO</Sexo>
<TipoDocumento>0</TipoDocumento>
<CodigoAfiliado>8</CodigoAfiliado>
<MensajeAfiliado />
</ConsultarAfiliadoResult>
</ConsultarAfiliadoResponse>
</soap:Body>
</soap:Envelope>
Here is a possible example of how you could go about getting the XML elements from your SOAP response (below) using SimpleXML which might be included in your PHP installation. Because I'm not sure what order of element data you need for the final output, you might need to rearrange the order of items in the output part below.
Also, in order for this to work, the $soapResponse variable in the code example needs to have no extra space before the start of the <?xml version="1.0" encoding="utf-8"?> line.
If you need to access other elements from the XML data, you should be able to do it with this pattern: $result->ConsultarAfiliadoResult->ElementNameHere.
<?php
$soapResponse = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ConsultarAfiliadoResponse xmlns="https://arssenasa.gob.do/">
<ConsultarAfiliadoResult>
<Contrato>8</Contrato>
<Cedula>013-0000655-6</Cedula>
<Nss>021827151</Nss>
<Nombres>MARGARET ADIRA</Nombres>
<Apellidos>SANTANA LORENZO DE CABRAL</Apellidos>
<IdEstado>0</IdEstado>
<CodigoFamiliar>8</CodigoFamiliar>
<IdRegimen xsi:nil="true" />
<Regimen>CONTRIBUTIVO</Regimen>
<FechaNacimiento>22/11/1973</FechaNacimiento>
<Edad>46</Edad>
<Sexo>FEMENINO</Sexo>
<TipoDocumento>0</TipoDocumento>
<CodigoAfiliado>8</CodigoAfiliado>
<MensajeAfiliado />
</ConsultarAfiliadoResult>
</ConsultarAfiliadoResponse>
</soap:Body>
</soap:Envelope>
XML;
// Remove <soap></soap> related tag information to get plain XML content
$xmlContent = preg_replace('/<soap:.*?>\n/', '', $soapResponse);
$xmlContent = preg_replace('/<\/soap:.*?>\n?/', '', $xmlContent);
// Note: there is an error with the xsi:nil="true" part, but that can be
// suppressed with the following line. If you need to deal with this error,
// more info here: https://www.php.net/manual/en/simplexml.examples-errors.php
libxml_use_internal_errors(true);
$result = new SimpleXMLElement($xmlContent);
// Print out results
printf(
"%s%s%s%s%s%s%s%s%s%s%s%s",
$result->ConsultarAfiliadoResult->Cedula,
$result->ConsultarAfiliadoResult->Nss,
$result->ConsultarAfiliadoResult->Nombres,
$result->ConsultarAfiliadoResult->Apellidos,
$result->ConsultarAfiliadoResult->IdEstado,
$result->ConsultarAfiliadoResult->CodigoFamiliar,
$result->ConsultarAfiliadoResult->Regimen,
$result->ConsultarAfiliadoResult->FechaNacimiento,
$result->ConsultarAfiliadoResult->Edad,
$result->ConsultarAfiliadoResult->Sexo,
$result->ConsultarAfiliadoResult->TipoDocumento,
$result->ConsultarAfiliadoResult->CodigoAfiliado
);
?>
Output:
$ php q22.php
013-0000655-6021827151MARGARET ADIRASANTANA LORENZO DE CABRAL08CONTRIBUTIVO22/11/197346FEMENINO08
After almost a journey of research I finally get the correct way to do it :
//The follow-up of my posting codes
.
.
.
$response = curl_exec($curl);
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//soapBody ')[0];
$array = json_decode(json_encode((array)$body), TRUE);
// in the case I want to grab only one data
//echo $array['ConsultarAfiliadoResponse']['ConsultarAfiliadoResult']['Cedula'];
// to display all data in the array
function dispaly_array_recursive($array_rec){
if($array_rec){
foreach($array_rec as $value){
if(is_array($value)){
dispaly_array_recursive($value);
}else{
echo $value.'<br>';
}
}
}
}
dispaly_array_recursive($array);
No more problem to save into database now

parse the soap xml response to array

I had used curl to call the soap server and i got the response like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GenerateAuthPasswordResponse xmlns="NepalTelecom.AuthGateway">
<GenerateAuthPasswordResult>abcd-efgh</GenerateAuthPasswordResult>
<ResultCode>1</ResultCode>
</GenerateAuthPasswordResponse>
</soap:Body>
</soap:Envelope>
and when i tried to parse the soap xml as:
$response = $this->SoapModel->soapCall($xml , $this->vas_wsdl_url);
$obj = simplexml_load_string($response);
echo $obj;die();
[Note: where $response is the above soap response provided in soap xml]
and i get the $obj as some error like this:
Severity: Warning
Message: simplexml_load_string(): namespace warning : xmlns: URI NepalTelecom.AuthGateway is not absolute
please any body could help so fix this issue.
Thank you in advance.
Try this.
<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GenerateAuthPasswordResponse >
<GenerateAuthPasswordResult>abcd-efgh</GenerateAuthPasswordResult>
<ResultCode>1</ResultCode>
</GenerateAuthPasswordResponse>
<GenerateAuthPasswordResponse >
<GenerateAuthPasswordResult>abcd-efgh</GenerateAuthPasswordResult>
<ResultCode>1</ResultCode>
</GenerateAuthPasswordResponse>
</soap:Body>
</soap:Envelope>';
$xml = simplexml_load_string($xml, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$ns = $xml->getNamespaces(true);
$soap = $xml->children($ns['soap']);
$res = $soap->Body->children();
print_r($res);

XML interpretation issue

I am working using soap, when the soap response is sent back all the < and > are represented using special characters.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UploadFileNew_XMLResponse xmlns="http://tempuri.org/GAPS_Uploader/FileUploader">
<UploadFileNew_XMLResult>
<?xml version="1.0" encoding="utf-8"?><Response><ResCode>1009</ResCode><Message>3 transaction(s) failed</Message><Errors><Error><Rownum>1</Rownum><Description>: Reference already exist </Description><Res_Code>59b1ebbc1c012 </Res_Code></Error><Error><Rownum>2</Rownum><Description>: Reference already exist </Description><Res_Code>59cb93d6c1d30 </Res_Code></Error><Error><Rownum>3</Rownum><Description>: Reference already exist </Description><Res_Code>59cbaca456589 </Res_Code></Error></Errors></Response>
</UploadFileNew_XMLResult>
</UploadFileNew_XMLResponse>
</soap:Envelope>
please how can i simplexml_load_string to process this result.
$response = htmlspecialchars_decode($response);
$parser = simplexml_load_string($response);
print_r($parser);
Change the order:
$parser = simplexml_load_string($response);
$response = htmlspecialchars_decode($parser->UploadFileNew_XMLResponse->UploadFileNew_XMLResult);
print_r($response);

Parsing XML in PHP with SimpleXML

I am trying to parse the below XML , i have tryed loads of different solutions, i have provided an example of what i have tryed. I have read the SimpleXML documents and i still cant get this right. In the Example below all im trying to do is Echo out a line in the XML.
<?php
$xmlstr = '
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<SubmitLeadResponse xmlns="https://test.com/">
<SubmitLeadResult>
<Result>C</Result>
<RedirectURL>https://testred.com</RedirectURL>
<ApplicantID>123</ApplicantID>
<ConfirmedPrice>0</ConfirmedPrice>
<PotentialPrice>0</PotentialPrice>
</SubmitLeadResult>
</SubmitLeadResponse>
</soap:Body>
</soap:Envelope>'
;
?>
<?php
$SubmitLeadResponse = new SimpleXMLElement($xmlstr);
echo $SubmitLeadResponse->SubmitLeadResult[0]->RedirectURL;
?>
You can try below code for SimpleXML
<?php
$xml ='<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<SubmitLeadResponse xmlns="https://test.com/">
<SubmitLeadResult>
<Result>C</Result>
<RedirectURL>https://testred.com</RedirectURL>
<ApplicantID>123</ApplicantID>
<ConfirmedPrice>0</ConfirmedPrice>
<PotentialPrice>0</PotentialPrice>
</SubmitLeadResult>
</SubmitLeadResponse>
</soap:Body>
</soap:Envelope>';
$get_xml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $xml);
$xml = simplexml_load_string($get_xml);
print"<pre>";
print_r((string)$xml->Body->SubmitLeadResponse->SubmitLeadResult->RedirectURL);
echo "<br /><br /><br />";
print_r($xml);
?>
I've changed your code a bit. Here's a working sample to get the RedirectURL:
<?php
$xmlstr = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<SubmitLeadResponse xmlns="https://test.com/">
<SubmitLeadResult>
<Result>C</Result>
<RedirectURL>https://testred.com</RedirectURL>
<ApplicantID>123</ApplicantID>
<ConfirmedPrice>0</ConfirmedPrice>
<PotentialPrice>0</PotentialPrice>
</SubmitLeadResult>
</SubmitLeadResponse>
</soap:Body>
</soap:Envelope>';
$doc = new DOMDocument();
$doc->loadXML( $xmlstr );
$RedirectURL = $doc->getElementsByTagName( "RedirectURL" );
$RedirectURL = $LoginResults->item(0)->nodeValue;
var_dump( $RedirectURL );
Sample provided from this source: There are also more informations to reading SOAP-envelopes without a soapclient
Please note that it's good practice to omit the php closing tag and stay in the php-context as long as possible to avoid unexpected outputs (linebreaks).
Your XML contains namespaced elements, so it's a little more complicated to parse. It can be done by passing the namespace values to children() like so:
Codepad demo
$SubmitLeadResponse = new SimpleXMLElement($xmlstr);
echo (string)$SubmitLeadResponse
->children('http://schemas.xmlsoap.org/soap/envelope/')
->Body
->children('https://test.com/')
->SubmitLeadResponse
->SubmitLeadResult
->RedirectURL;
Outputs
https://testred.com
Note: SimpleXML doesn't like new lines before the XML string, so remove the new line, making it:
$xmlstr = '<?xml version="1.0" encoding="utf-8"?>

How do I read SOAP reply Envelope by PHP

How do I read the error_code from this SOAP reply Envelope? My PHP version is: 5.2.0.
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<Response xmlns="http://xxx.gateway.xxx.abcd.com">
<return>
<transaction_id>1234567</transaction_id>
<error_code>109</error_code>
</return>
</Response>
</soap:Body>
</soap:Envelope>
I just need to read the value of error_code tag.here the value is :109
I am using nusoap. I used the below code but not working properly:
$response=htmlspecialchars($client->response, ENT_QUOTES);
$xml = simplexml_load_string($response);
$ns = $xml->getNamespaces(true);
$soap = $xml->children($ns['soap']);
$error_code = $soap->body->children($ns['error_code']);
<?php
$string = <<<XML
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<Response xmlns="http://xxx.gateway.xxx.abcd.com">
<return>
<transaction_id>1234567</transaction_id>
<error_code>109</error_code>
</return>
</Response>
</soap:Body>
</soap:Envelope>
XML;
$xml = new SimpleXMLElement($string);
$xml->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
$body = $xml->xpath("//soap:Body");
$error_code = (string)$body[0]->Response->return->error_code;
print_r($error_code);
?>
OR
$xml = simplexml_load_string($string);
$error_code = (string)$xml->children('soap', true)
->Body
->children()
->Response
->return
->error_code;

Categories