I got a problem with this SOAP response :
<?xml version="1.0" encoding="utf-8"?>
<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:Body>
<GetStockResponse xmlns="http://retailexpress.com.au/">
<GetStockResult>base64Binary</GetStockResult>
</GetStockResponse>
</soap:Body>
</soap:Envelope>
So, my code for handle this response look like this :
public function getStock()
{
$soapClient = $this->getSoapClient();
$xmlRequest = soapHead . '<ret:GetStock></ret:GetStock>' . soapFoot;
try {
$request = $soapClient->__anotherRequest('GetStock', $xmlRequest);
$requestDecoded = base64_decode($request);
$stock = gzdecode($requestDecoded);
} catch (SoapFault $e ){
var_dump($e);
exit();
}
$response = new Response($stock);
$response->headers->set('Content-Type', 'text/xml');
return $response;
}
With this code I always got this error :
Warning: gzdecode(): data error
But if I var_dump $request decoded and I try to gzdecode this string it works !
I can't find my mistake here ...
And for each try I got to wait 5 minutes ^^'
I hope I'm enough understandable
Thanks by advance
Tanguy
I find the solution,
The soap response is an xml so you need to create a SimpleXmlElement to get the content
$request = $soapClient->__anotherRequest('GetStock', $xmlRequest);
$xmlRequest = new \SimpleXMLElement($request);
$response = $xmlRequest->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children()->GetStockResponse;
$result = (string) $response->GetStockResult;
$requestDecoded = base64_decode($result);
$stock = gzdecode($requestDecoded);
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 have been spending hours trying to parse a SOAP response that I have no control over. I have tried numerous methods I found on SO with no luck.
Here is the response body I get from edge browser:
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:gXMLQueryResponse xmlns:ns1="urn:com-photomask-feconnect-IFeConnect" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<return xsi:type="xsd:string"><?xml version = '1.0' encoding = 'UTF-8'?>
<ROWSET>
<ROW num="1">
<CUSTOMER_NAME>HITACHI</CUSTOMER_NAME>
</ROW>
</ROWSET>
</return>
</ns1:gXMLQueryResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I'm trying to get the CUSTOMER_NAME value.
Here is the code I am using:
$client = new SoapClient($urla, array('trace' => 1));
try {
$result = $client->__soapCall("gXMLQuery", $params);
$response = ($client->__getLastResponse());
$xml = simplexml_load_string($response);
$rows = $xml->children('SOAP-ENV', true)->Body->children('ns1', true)->gXMLQueryResponse->return->ROWSET->ROW;
foreach ($rows as $row)
{
$customer = $row->CUSTOMER_NAME;
echo $customer;
}
} catch (SoapFault $e) {
}
return is a string, you need to parse it first before you can access it using SimpleXML.
First you need to decode the string using html_entity_decode, after that you can load the decoded string with simplexml_load_string:
$return = $xml->children('SOAP-ENV', true)->Body->children('ns1', true)->gXMLQueryResponse->return;
$decodedReturn = html_entity_decode($return, ENT_QUOTES | ENT_XML1, 'UTF-8');
$rowset = simplexml_load_string($decodedReturn);
echo $rowset->ROW->CUSTOMER_NAME;
I have the below SOAP XML, Im trying to access the vehicle details with the soap header authentication. I have tried the below code. I think, Im missing something on this. Can u help
SOAPAction: "http://abcddetails.org/getVehicleDetails"
<?xml version="1.0" encoding="utf-8"?>
<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>
<UserIdentifierSoapHeaderIn xmlns="http://abcddetails.org/">
<UserName>string</UserName>
<Password>string</Password>
</UserIdentifierSoapHeaderIn>
</soap:Header>
<soap:Body>
<getVehicleDetails xmlns="http://abcddetails.org/">
<request>
<SystemCode>int</SystemCode>
<UserID>string</UserID>
<PlateInfo>
<PlateNo>long</PlateNo>
<PlateOrgNo>long</PlateOrgNo>
<PlateColorCode>int</PlateColorCode>
</PlateInfo>
<ChassisNo>string</ChassisNo>
</request>
</getVehicleDetails>
</soap:Body>
PHP code along with the SOAP Header, I have created as the below.
<?php
$wsdl = "http://abcddetails.org/InspectionServices.asmx?WSDL";
$client = new SoapClient($wsdl, array('trace'=>1)); // The trace param will show you errors stack
$auth = array(
'Username'=>'XXXXX',
'Password'=>'XXXXX',
);
$header = new SOAPHeader($wsdl, 'UserIdentifierSoapHeaderIn', $auth);
$client->__setSoapHeaders($header);
// web service input params
$request_param = array(
"SystemCode" => 4,
"UserID" => "TEST",
"ChassisNo" => '1N4AL3A9XHC214925'
);
$responce_param = null;
try
{
$responce_param = $client->getVehicleDetails($request_param);
//$responce_param = $client->call("webservice_methode_name", $request_param); // Alternative way to call soap method
}
catch (Exception $e)
{
echo "<h2>Exception Error!</h2>";
echo $e->getMessage();
}
print_r($responce_param);
?>
Can u guide if anything I have written wrong here in this.
You can use the __soapCall method like this:
$result = $client->__soapCall('webserviceMethodeName', ['parameters' => $params]);
In your case a soap action would be invoked like this:
$responce_param = $client->__soapCall('getVehicleDetails', ['parameters' => $request_param]);
Read more
I am trying to make a client request for a soap web service, and when I try to create the xml with simplexml_load_string it says this:
Error: Cannot create object
With no any other errors, so I can't figure it out what am I doing wrong, my code is bellow, I hope you can help me to solve this issue
<?php
$produccion = false; //Cambiar a verdadero por producction
$url = "http://ws.maxirest.com/wsclientes/wscli06896.php";
//print_r($_POST);
$posts = $_POST;
if ($produccion == false) {
$posts['nombre'] =
$posts['apellido'] =
$posts['direccion'] =
$posts['pisodto'] =
$posts['localidad'] =
$posts['partido'] =
$posts['provincia'] =
$posts['telefono'] =
$posts['celular'] =
"PRUEBA";
}
$Datos = "<cliente>
<nombre>".$posts['nombre']."</nombre>
<apellido>".$posts['apellido']."</apellido>
<calle>".$posts['direccion']."</calle>
<altura>".$posts['altura']."</altura>
<pisodto>".$posts['pisodto']."</pisodto>
<localidad>".$posts['localidad']."</localidad>
<partido>".$posts['partido']."</partido>
<provincia>".$posts['provincia']."</provincia>
<telefono>".$posts['telefono']."</telefono>
<celular>".$posts['celular']."</celular>
<num_tarjeta>".$posts['num_tarjeta']."</num_tarjeta>
</cliente>";
$myXMLData = '<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.maxisistemas.com.ar">
<soapenv:Header/>
<soapenv:Body>
<ws:AltaSolicitud soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<cXml>'.$Datos.'</cXml>
<Clave>123ClubMilaMREST5</Clave>
</ws:AltaSolicitud>
</soapenv:Body>
</soapenv:Envelope>';
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object"); //<-Here is the error
$client = new SoapClient($url);
$result1 = $client->AltaSolicitud($xml);
$result2 = $client->ConsultaPuntos($xml);
?>
I can't get an answer but
=> "ERROR. ACCESO NO PERMITIDO"
But with the right credentials and data you should be able to get the information you need with below class.
Simply set your data in the setData() function / call it first and then call AltoSolicitud() with Clave as parameter
class Request extends \SoapClient
{
public $Datos;
public function __construct(array $options = [], $wsdl = 'http://ws.maxirest.com/wsclientes/wscli06896.php?wsdl')
{
$options = [
'features' => 1,
];
parent::__construct($wsdl, $options);
}
/**
* #param string $Clave
* #return string
*/
public function AltaSolicitud()
{
$Data = $this->getData();
try {
return $this->__soapCall('AltaSolicitud', [
$Data
]);
} catch (\SoapFault $e) {
return ($e->getMessage());
}
}
public function setData($posts,$produccion = false)
{
if ( ! $produccion) {
$posts['nombre'] =
$posts['apellido'] =
$posts['direccion'] =
$posts['pisodto'] =
$posts['localidad'] =
$posts['partido'] =
$posts['provincia'] =
$posts['telefono'] =
$posts['celular'] =
"PRUEBA";
}
$Datos = "<cliente><nombre>".$posts['nombre']."</nombre>
<apellido>".$posts['apellido']."</apellido>
<calle>".$posts['direccion']."</calle>
<altura>".$posts['altura']."</altura>
<pisodto>".$posts['pisodto']."</pisodto>
<localidad>".$posts['localidad']."</localidad>
<partido>".$posts['partido']."</partido>
<provincia>".$posts['provincia']."</provincia>
<telefono>".$posts['telefono']."</telefono>
<celular>".$posts['celular']."</celular>
<num_tarjeta>".$posts['num_tarjeta']."</num_tarjeta></cliente>";
$Clave = '123ClubMilaMREST5';
$myXMLData = <<<XML
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.maxisistemas.com.ar">
<soapenv:Header/>
<soapenv:Body>
<ws:AltaSolicitud soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<cXml xsi:type="xsd:string">' . str_replace(PHP_EOL,'',$Datos) . '</cXml>
<Clave xsi:type="xsd:string">' . $Clave . '</Clave>
</ws:AltaSolicitud>
</soapenv:Body>
</soapenv:Envelope>
XML;
$this->Datos = $myXMLData;
return $this;
}
/**
* #param string $Cod_Tarj
* #param string $Clave
* #return string
*/
public function ConsultaPuntos($Cod_Tarj, $Clave)
{
return $this->__soapCall('ConsultaPuntos', [$Cod_Tarj, $Clave]);
}
public function getData(){
return $this->Datos;
}
$request = (new Request)->setData($_POST,false)->AltaSolicitud();
var_dump($request);
#Ricardo
I was able to make your code work by adding "wsdl" to the url. After this change I did not see the error "Cannot create object".
$url = "http://ws.maxirest.com/wsclientes/wscli06896.php?wsdl";
I made some other minor changes, but I don't think they are important:
$xml = simplexml_load_string( $myXMLData ); //or die("Error: Cannot create object"); //<-Here is the error
$client = new SoapClient( $url , array('trace' => 1 ));
$result1 = $client->AltaSolicitud($xml);
echo "Response:\n" . $client->__getLastResponse() . "\n";
And the result was the same "ERROR. ACCESO NO PERMITIDO" already noted. To me it appears that the soap parameter <Clave>123ClubMilaMREST5</Clave>is incorrect or expired. I noticed this because the word is almost the same in Italian (chiave = clave = key). I assume this is an API key like many web services require?
SOAP Response
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:AltaSolicitudResponse xmlns:ns1="http://ws.maxisistemas.com.ar">
<return xsi:type="xsd:string">ERROR. ACCESO NO PERMITIDO</return>
</ns1:AltaSolicitudResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>