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
Related
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'];
I am using below code for SOAP request.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://example.com?WSDL",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://Xyz.Abc\" xmlns:ns2=\"http://tempuri.org/\"><SOAP-ENV:Body><ns2:GetStatus><ns1:ReferenceNo>12345</ns1:ReferenceNo></ns2:GetStatus></SOAP-ENV:Body></SOAP-ENV:Envelope>",
CURLOPT_HTTPHEADER => array(
"Content-Type: text/xml"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Response:
Getting below response when I set header('Content-type: application/xml'); in php script which is correct.
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header>...</env:Header>
<env:Body>
<GetStatusResponse xmlns:s1="http://Xyz.Abc" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://tempuri.org/" xmlns="http://tempuri.org/">
<s1:StatusResponse>
<s1:Test ResponseCode="INPROGRESS" ResponseMessage="Reference no. 12345"/>
</s1:StatusResponse>
</GetStatusResponse>
</env:Body>
</env:Envelope>
How can I extract Body values from the response without just printing on browser?
Here is what I tried
Remove xml header and parse response string by simplexml_load_string method.
$xml = simplexml_load_string($response);
echo $xml;
$json = json_encode($response);
$arr = json_decode($json,true);
print_r($arr);
I also tried with SimpleXMLElement, but, it's printing empty response:
$test = new SimpleXMLElement($response);
echo $test;
But, it's printing empty result.
SimpleXML is an object. It isn't the full XML string as you might think. Try this.
//Cast to string to force simpleXml to convert into a string
$xmlString = $xml->asXML();
echo $xmlString . "\n";
I'm pretty sure you can't do this because $response is XML. Trying to json_encode it doesn't make sense.
$json = json_encode($response);
I did this:
<?php
$x = '<?xml version="1.0" ?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header>...</env:Header>
<env:Body>
<GetStatusResponse xmlns:s1="http://Xyz.Abc" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://tempuri.org/" xmlns="http://tempuri.org/">
<s1:StatusResponse>
<s1:Test ResponseCode="INPROGRESS" ResponseMessage="Reference no. 12345"/>
</s1:StatusResponse>
</GetStatusResponse>
</env:Body>
</env:Envelope>';
$xml = simplexml_load_string($x);
echo $xml->asXml();
echo "\n";
And I get this output:
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
<env:Header>...</env:Header>
<env:Body>
<GetStatusResponse xmlns:s1="http://Xyz.Abc" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://tempuri.org/" xmlns="http://tempuri.org/">
<s1:StatusResponse>
<s1:Test ResponseCode="INPROGRESS" ResponseMessage="Reference no. 12345"/>
</s1:StatusResponse>
</GetStatusResponse>
</env:Body>
</env:Envelope>
This explains how to specify namespaces.
https://www.php.net/manual/en/simplexmlelement.attributes.php
$xml->registerXPathNamespace('e', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('s', 'http://Xyz.Abc');
$result = $xml->xpath('//s:Test');
$response = $result[0]->attributes();
echo "Response Code = " . $response['ResponseCode'] . "\n";
echo "Response Message = " . $response['ResponseMessage'] . "\n";
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);
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);
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"?>