I am working in a public SOAP to show some data from that API to my website.
The orginal API in wsdl and I used SOAP UI and its run perfectly in SOAPUI but in PHP, it works too but it dumps all the data as whole but i want to show the objects seperately.
Header from SOAPUI
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.RSS.tadawul.com">
<soapenv:Header/>
<soapenv:Body>
<ser:getDetailQuoteForCompany>
<companyId>****</companyId>
<secureKey>*****</secureKey>
</ser:getDetailQuoteForCompany>
</soapenv:Body>
</soapenv:Envelope>
In PHP, I am using CURL
This is my PHP Code
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://webservices.tadawul.com.sa/Tadawul_WebAPI/services/GetDetailQuote",
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 =>'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://services.RSS.tadawul.com">
<soapenv:Header/>
<soapenv:Body>
<ser:getDetailQuoteForCompany>
<companyId>****</companyId>
<secureKey>*****</secureKey>
</ser:getDetailQuoteForCompany>
</soapenv:Body>
</soapenv:Envelope>',
CURLOPT_HTTPHEADER => array(
'SOAPAction: add',
'Content-Type: text/xml',
'Cookie: TS013c7d51=0102d17fad3e1f67bf447921624346888618df0fedeec12518b1d7331061faea4f17793ef2558e8e6c8e3e926a4ba92d61983b194a'
),
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
echo $response;
echo response works too, it dumps all the details then i used parser which is not working.
$response1 = str_replace("<soapenv:Body>","",$response);
$response2 = str_replace("</soapenv:Body>","",$response1);
$parser = simplexml_load_string($response2);
echo $parser;
This is the output of the parser.
SimpleXMLElement Object ( )
Some of the other methods i tried which didnt work.
$final = new SimpleXMLElement($response);
echo $final->getDetailQuoteForCompanyReturn[0]->prevClosePrice;
I tried to used JSON, not worked
$result = json_decode($response);
echo $result;
print_r($result);
Tried using for loop, didnt work
foreach ($response as $key) {
echo $key;
}
Where i made the mistake?
Related
Good afternoon friends,
I need your knowledge, I have a curl php function which responds perfectly, but it has been a real headache for me to pass those results to a JSON or ARRAY, I have tried several ways without success,
the response i get from curl XML is this
0<?xml version="1.0" encoding="UTF-8"?> <mensaje> <version>2019.11.04</version> <nca-respuesta> <codigo-Error>0</codigo-Error> <texto-Error>Transaccion Exitosa</texto-Error> <transaccion> <boleta>2414</boleta> <tipo>1</tipo> <monto>24990</monto> <vendedor>111111</vendedor> <rutcp>1111111</rutcp> <numero-transaccion>2414</numero-transaccion> <folio-DTE>11111111</folio-DTE> <tipo-documento>2</tipo-documento> <fecha>04/11/2022</fecha> <sucursal>37</sucursal> <terminal>105</terminal> <factura-normal>0014122272 </factura-normal> <factura-moto> </factura-moto> <rut-emisor>111111</rut-emisor> </transaccion> <fidelizacion> <rut-bonificacion>111111</rut-bonificacion> </fidelizacion> <regalo> </regalo> <articulos> <articulo> <item>1</item> <upc>2000388411434</upc> <precio>16990</precio> <cantidad-comprada>1</cantidad-comprada> <rmc>2</rmc> <servicios> </servicios> <descuento> <tipo>1</tipo> <monto>4495</monto> </descuento> <cantidad-maxima-devolver>1</cantidad-maxima-devolver> <monto-maximo-devolver>9000000</monto-maximo-devolver> <rut-anfitrion>111111111</rut-anfitrion> </articulo> <articulo> <item>2</item> <upc>2000369667645</upc> <precio>16990</precio> <cantidad-comprada>1</cantidad-comprada> <rmc>2</rmc> <servicios> </servicios> <descuento> <tipo>1</tipo> <monto>4495</monto> </descuento> <cantidad-maxima-devolver>1</cantidad-maxima-devolver> <monto-maximo-devolver>9000000</monto-maximo-devolver> <rut-anfitrion>16665688</rut-anfitrion> </articulo> </articulos> <fpagos> <fpago> <tipo>4</tipo> <nombre>Tarjeta de Credito Bancaria</nombre> <marca>MA</marca> <tipo-tarjeta>C</tipo-tarjeta> <rut>14122272</rut> <numero-tarjeta>0</numero-tarjeta> <tipo-cuota>1</tipo-cuota> <numero-cuotas>1</numero-cuotas> <vencimiento>1111</vencimiento> <autorizacion>790425</autorizacion> <codigo-unico>111111111111111111</codigo-unico> <monto>24990</monto> <monto-devuelto>0</monto-devuelto> </fpago> </fpagos> <fpromocion> <id-cliente>111111111111</id-cliente> <tipo-id-cliente>1</tipo-id-cliente> <email-transaccion>cpruebas#pruebas.com</email-transaccion> </fpromocion> </nca-respuesta> </mensaje>
The other thing that I have tried is to pass that result to text to delete the line of text "0 " with $str but I have not had any success either,
I don't know what else to try, I leave you part of the function
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => '',
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:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' xmlns:xsi='' xmlns:xsd='' xmlns:ns2='' xmlns:ser='http://service/'>
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ser:NCAtomaticaDTE>
<arg0>
<![CDATA[
<mensaje/>
<nca-requerimiento>
<programa>
<version>Version VER6207I 23/01/2012 09:30</version>
<timeout>11</timeout>
</programa>
<datos-originales>
<fecha>$fecha_compra_boleta_formateada</fecha>
<sucursal>$sucursal_boleta</sucursal>
<terminal>$numero_terminal_boleta</terminal>
<numero-boleta>$numero_folio_boleta</numero-boleta>
<folio></folio>
<rmc></rmc>
</datos-originales>
</nca-requerimiento>
</mensaje>
]]>
</arg0>
</ser:NCAtomaticaDTE>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>",
CURLOPT_HTTPHEADER => array(
'SOAPaction: kkkk',
'Content-Type: application/xml'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
I tried to pass the result to json or array with no success, I also tried to pass the result to text
so after some great help, I've managed to get the script doing everything I need it to, but I need help with the next bit.
Please see my script below.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://www.xxxxx.com/webAPI/api/stock',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS =>'<?xml version="1.0" encoding="utf-8" ?>
<traderapi>
<token>T1a5c3t9</token>
<variant>Clearbank ltd</variant>
<pon>X</pon>
</traderapi>',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer T1a5c3t9',
'Content-Type: application/xml'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response
?>
I get the
Picture of Chrome results
The results that are displayed as this "210-AZBVTBC"
However in the code show this (as per the picture) "210-AZBVTBC4"
You can see I do a simple echo $response. How do I parse the information so I can show and manipulate how I show the individual tags. For example
echo ''.$response->Sku.'';
the result is a string not a file.
try using simplexml_load_string instead of simplexml_load_file.
$Products = simplexml_load_string($response);
I am trying to send an API request using a XML body and get a response back in xml.
When I test this in Postman the respone is as XML and I am able to see the element names. I used the postman code function to get the code below for PHP.
However the response in PHP curl is a string with element values. There are no element names and the response is one long string with no separators
Any help with this will be greatly appreciated
My code:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://myUrl.com',
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 =>'<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://myApiService.webservice.gbs">
<soapenv:Body>
<api:getNameOptions>
<api:name>36534367</api:name>
<api:surname>5000033</api:surname>
</api:getNameOptions>
</soapenv:Body>
</soapenv:Envelope>',
CURLOPT_HTTPHEADER => array(
'Content-Type: text/xml; charset=utf-8',
'SOAPAction: urn:getNameOptions'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
PHP Response
500000466280AGI/B1671025282958passedCGI_BTT_02 nop 1/1/1/7/6/10/1CGI/B167/B131/2/2ABCXSDARDCGI_BEST_02:1-1-1-7-6(SP4A) AGB/B167/B131/2, OUT 2 Tray 1(2)
SOAP in PHP is a bit difficult but it's much better to use the build in SOAP class and read the WSDL file to get the complete structure and work with the SOAP api.
When you look at the documentation: https://www.php.net/manual/en/book.soap.php
There is an example that could match your problem.
$soapClient = new SoapClient("https://soapserver.example.com/blahblah.asmx?wsdl");
// Prepare SoapHeader parameters
$sh_param = array(
'Username' => 'username',
'Password' => 'password'
);
$headers = new SoapHeader('http://soapserver.example.com/webservices', 'UserCredentials', $sh_param);
// Prepare Soap Client
$soapClient->__setSoapHeaders(array($headers));
With this example you can login and set the credentials and set it as soap header.
line below fixed the issue
$oXML = new SimpleXMLElement( $response );
header( 'Content-type: text/xml' );
echo $oXML->asXML();
Whenever I use Postman to make a soap post request, I get back the desired data. Using Guzzle, no data is returned. Im new to SOAP and using the resources online to go along.
I have omitted the variables for ease of read.
$xml = (
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:app="<ACTION-URL>">
<soapenv:Body>
<app:' . $functionName . '>
<request>'
. $requestBody .
'<authentication>
<username>'. $authObject->username .'</username>
<password>'. $authObject->password .'</password>
<user_id>'. $authObject->userId .'</user_id>
<dealer_id>'. $authObject->clientBranchId .'</dealer_id>
</authentication>
</request>
</app:' . $functionName . '>
</soapenv:Body>
</soapenv:Envelope>'
);
private function makeSOAPRequest($xml)
{
$client = new \GuzzleHttp\Client();
$options = [
'headers' => [
'Content-Type' => 'text/xml; charset=utf-8'
],
'body' => $xml,
'Authenticate' => [env('USERNAME'), env('PASSWORD')]
];
$url = env('ROSETTA_API');
$promise = $client->requestAsync('POST', $url, $options);
$response = $promise->wait();
$xml = simplexml_load_string($response->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);
if ($xml) {
$json = json_encode($xml);
return json_decode($json, true);
}
return false;
}
Calling makeSOAPRequest(..), I get back false. Using the same xml data in Postman, data is returned. Is there anything I've missed in the request header?
Edit to use cURL
// Copied from Postman:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://<URL>",
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 => $xml,
CURLOPT_HTTPHEADER => array(
"Cookie: PHPSESSID=6419f1d96025a4a2c4d454de33fc6820"
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response; // xml data in string format.
cUrl does work but not Guzzle. How to return as json? When I use simplexml_load_string, it's empty.
Try to use below parameters in your curl:
CURLOPT_SSL_VERIFYPEER => 1
CURLOPT_POST => true
// IF NEEDED
CURLOPT_HTTPAUTH => CURLAUTH_ANY
// IF NEEDED
CURLOPT_USERPWD => $soapUser.":".$soapPassword)
For Checking Error After curl_exec and before curl_close
if( curl_errno($ch) ){
print_r(curl_error($curl));
}
In add these headers in your header if needed:
"accept" => "*/*",
// IF NEEDED
"accept-encoding" => "gzip, deflate"
Add your request code in try catch block:
try{
//request code
}
catch(Exception $e){
print_r($e->getCode());
print_r($e->getMessage());
}
I am calling a web service at
http://test.dnb.avantimedns.se/drombolig/webservices/autoprospectservice.asmx?op=SaveAutoprospect
API KEY: de2de92-5d8c-4dcc-8573-9354b96ba683
OBJECT ID: 90160211
but it is not returning valid response. Below is my code. Kindly help in fixing.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://test.dnb.avantimedns.se/drombolig/webservices/autoprospectservice.asmx?op=SaveAutoprospect",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '{\n \"autoprospect\": \"{\\"SendAdditionalProspects\\":false,\\"RequestsEconomicalAdvice\\":false,\\"RequestsAssessment\\":false,\\"UserEmailsuccess\\":true,\\"ApprovesContact\\":true,\\"ObjectId\\":\\"90160211\\",\\"Source\\":\\"Company\\",\\"Name\\":\\"Test Testsson\\",\\"Email\\":\\"test#test.com\\",\\"ZipCode\\":\\"12345\\",\\"Phone\\":\\"1234567890\\",\\"Message\\":\\"Test\\"}\",\n \"apikey\": \"de2de92-5d8c-4dcc-8573-9354b96ba683\"\n \n}',
CURLOPT_HTTPHEADER => array("content-type: application/json"),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Looks like it returns valid response (in my case it returns exception and stack). The issue seems to be on api call side.
The response is looking 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" ▶
at System.Xml.XmlTextReaderImpl.Throw(Exception e)\r\n
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)\r\n
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()\r\n
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()\r\n
at System.Xml.XmlTextReaderImpl.Read()\r\n
at System.Xml.XmlTextReader.Read()\r\n
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()\r\n
at System.Xml.XmlReader.MoveToContent()\r\n
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()\r\n
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()\r\n
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()\r\n
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)\r\n
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()\r\n
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)\r\n
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortP ▶
--- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>