I have this return from a SOAP webservice :
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:historyResponse xmlns:ns2="XXXXXXXXXX">
<return>
<userFullname>AGENT</userFullname>
<date>2018-08-01T17:24:20.948+02:00</date>
<stateName>Préparé</stateName>
</return>
<return>
<userFullname>PARAPHEUR</userFullname>
<date>2018-08-01T17:24:21.039+02:00</date>
<stateName>Envoyé pour signature</stateName>
</return>
<return>
<userFullname>Administrator</userFullname>
<date>2018-08-01T17:24:21.228+02:00</date>
<stateName>Signé</stateName>
</return>
<return>
<userFullname>PARAPHEUR</userFullname>
<date>2018-08-01T17:24:21.324+02:00</date>
<stateName>Classé</stateName>
</return>
</ns2:historyResponse>
</soap:Body>
</soap:Envelope>
When I consume this webservice through PHP and CURL I just get a string like this (var dump) :
string(728) "<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:historyResponse xmlns:ns2="http://sei.ws.fast.cdc.com/"><return><userFullname>AGENT EDISSYUM</userFullname><date>2018-08-01T17:24:20.948+02:00</date><stateName>Préparé</stateName></return><return><userFullname>PARAPHEUR </userFullname><date>2018-08-01T17:24:21.039+02:00</date><stateName>Envoyé pour signature</stateName></return><return><userFullname>Administrator </userFullname><date>2018-08-01T17:24:21.228+02:00</date><stateName>Signé</stateName></return><return><userFullname>PARAPHEUR </userFullname><date>2018-08-01T17:24:21.324+02:00</date><stateName>Classé</stateName></return></ns2:historyResponse></soap:Body></soap:Envelope>"
How could I have from this string an array of "return" ?
You can use simplexml_load_string() and json functions to convert it to an array. (note that you need to replace the colons as this function doesn't recognize xml with namespaces for some reason)
$response = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:historyResponse xmlns:ns2="http://sei.ws.fast.cdc.com/"><return><userFullname>AGENT EDISSYUM</userFullname><date>2018-08-01T17:24:20.948+02:00</date><stateName>Préparé</stateName></return><return><userFullname>PARAPHEUR </userFullname><date>2018-08-01T17:24:21.039+02:00</date><stateName>Envoyé pour signature</stateName></return><return><userFullname>Administrator </userFullname><date>2018-08-01T17:24:21.228+02:00</date><stateName>Signé</stateName></return><return><userFullname>PARAPHEUR </userFullname><date>2018-08-01T17:24:21.324+02:00</date><stateName>Classé</stateName></return></ns2:historyResponse></soap:Body></soap:Envelope>';
//I'm not the author of this regex ;)
$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = simplexml_load_string($xml);
$json = json_encode($xml);
$responseArray = json_decode($json,true);
echo '<pre>';
print_r($responseArray);
Hope it helps!! Feel free to ask if you have any doubts :)
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 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
I´m trying to extract the RecordID = "1014276" from a tag
I tried with :
$result = curl_exec($ch);
curl_close($ch);
$xml2 = simplexml_load_string($result);
echo $latitude = (string) $xml2['RecordID'];
This is the XML response:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
<ns1:createDataResponse xmlns:ns1="http://3e.pl/ADInterface">
<StandardResponse RecordID="1014276" xmlns="http://3e.pl/ADInterface"/>
</ns1:createDataResponse>
</soap:Body>
</soap:Envelope>
This involves a bit more than just accessing the attribute, first you have to select the correct element. Using XPath is the most comment way in this sort of structure.
As this has a default namespace defined for the data, you will need to register this with the SimpleXMLElement first (using $xml2->registerXPathNamespace("ns1","http://3e.pl/ADInterface");.
You can then find the element using the XPAth expression //ns1:StandardResponse. As the xpath() method returns a list of found elements, use [0] to just extract the first match. You should then be able to extract the attribute as in your code using the resultant element...
$xml2 = simplexml_load_string($result);
$xml2->registerXPathNamespace("ns1","http://3e.pl/ADInterface");
$response = $xml2->xpath("//ns1:StandardResponse")[0];
echo (string) $response['RecordID'];
You can apporach this as
$xml = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body>
<ns1:createDataResponse xmlns:ns1="http://3e.pl/ADInterface">
<StandardResponse RecordID="1014276" xmlns="http://3e.pl/ADInterface"/>
</ns1:createDataResponse>
</soap:Body>
</soap:Envelope>';
$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $values, $index);
xml_parser_free($p);
echo $values[3]['attributes']['RECORDID'];
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);
Been struggling all day trying to figure out a way to parse this xml with php:
$xml = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns1:recherchePointChronopostResponse xmlns:ns1="http://cxf.rechercheBt.soap.chronopost.fr/">
<return>
<errorCode>0</errorCode>
<errorMessage>Code retour OK</errorMessage>
<listePointRelais>
<accesPersonneMobiliteReduite>true</accesPersonneMobiliteReduite>
<actif>true</actif>
<adresse1>4 RUE DE MONTESSUY</adresse1>
<adresse2/>
<adresse3/>
<codePays>FR</codePays>
<codePostal>75007</codePostal>
<coordGeolocalisationLatitude>48.8597222222</coordGeolocalisationLatitude>
<coordGeolocalisationLongitude>2.304166666670</coordGeolocalisationLongitude>
<distanceEnMetre>852</distanceEnMetre>
<identifiant>2102R</identifiant>
<indiceDeLocalisation/>
<listeHoraireOuverture>
<horairesAsString>08:00-12:00 12:00-20:00</horairesAsString>
<jour>7</jour>
<listeHoraireOuverture>
<debut>08:00</debut>
<fin>12:00</fin>
</listeHoraireOuverture>
<listeHoraireOuverture>
<debut>12:00</debut>
<fin>20:00</fin>
</listeHoraireOuverture>
</listeHoraireOuverture>
</listePointRelais>
<qualiteReponse>2</qualiteReponse>
<wsRequestId/>
</return>
</ns1:recherchePointChronopostResponse>
</soap:Body>
</soap:Envelope>';
and here is the php i use:
$soap = simplexml_load_string($xml);
$soap->registerXPathNamespace('soap', 'http://cxf.rechercheBt.soap.chronopost.fr/');
foreach ($soap->xpath('//ns1:errorMessage') as $val) {
echo $val . "<br>";
}
But i keep having a blank page!! do you please know what is wrong?
I also tried to follow this post converting SOAP XML response to a PHP object or array, in vain!
Thanks
Give this a shot...
$xml = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns1:recherchePointChronopostResponse xmlns:ns1="http://cxf.rechercheBt.soap.chronopost.fr/">
<return>
<errorCode>0</errorCode>
<errorMessage>Code retour OK</errorMessage>
<listePointRelais>
<accesPersonneMobiliteReduite>true</accesPersonneMobiliteReduite>
<actif>true</actif>
<adresse1>4 RUE DE MONTESSUY</adresse1>
<adresse2/>
<adresse3/>
<codePays>FR</codePays>
<codePostal>75007</codePostal>
<coordGeolocalisationLatitude>48.8597222222</coordGeolocalisationLatitude>
<coordGeolocalisationLongitude>2.304166666670</coordGeolocalisationLongitude>
<distanceEnMetre>852</distanceEnMetre>
<identifiant>2102R</identifiant>
<indiceDeLocalisation/>
<listeHoraireOuverture>
<horairesAsString>08:00-12:00 12:00-20:00</horairesAsString>
<jour>7</jour>
<listeHoraireOuverture>
<debut>08:00</debut>
<fin>12:00</fin>
</listeHoraireOuverture>
<listeHoraireOuverture>
<debut>12:00</debut>
<fin>20:00</fin>
</listeHoraireOuverture>
</listeHoraireOuverture>
</listePointRelais>
<qualiteReponse>2</qualiteReponse>
<wsRequestId/>
</return>
</ns1:recherchePointChronopostResponse>
</soap:Body>
</soap:Envelope>';
$doc = new DOMDocument();
$doc->loadXML( $xml );
$results = $doc->getElementsByTagName( "errorMessage" );
$errorMessage = $results->item(0)->nodeValue;
echo $errorMessage;