convert curl xml response to json or array in php - php

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

Related

PHP Curl and XML Response - Updated

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);

xml element names missing in response using php curl

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();

Trouble with Param arguments for an Api

Im trying to get all cities of a specific country from an API(https://countriesnow.space/). Im using Php and curl but the result says:
{
"error": true,
"msg": "missing param (country)"
}
Im using a script which is given by but it does not work: https://documenter.getpostman.com/view/1134062/T1LJjU52#4829d16f-0f4e-43ec-886e-68ebad1221d8
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://countriesnow.space/api/v0.1/countries/cities',
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 =>'{
"country": "nigeria"
}',
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Could anyone tell me whats wrong here? Really cant tell whats the issue.
cURL will automatically set the Content-Type to application/x-www-form-urlencoded, when you pass a string value for CURLOPT_POSTFIELDS.
But this is not supposed to be form data, but JSON. Add
CURLOPT_HTTPHEADER => ['Content-Type: application/json']
to your cURL options, to let the API know you are in fact sending JSON.

cURL: wait for response until it is processed by api

everybody,
I am using the following code for synchronizing data with an API ($method= POST) and then I call using the GET method ($method= GET) to print the result of the synchronization:
function sendCurl ($fileName, $method)
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $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 => $method,
CURLOPT_POSTFIELDS => array('file' => new CURLFILE($fileName)),
CURLOPT_HTTPHEADER => array(
"Authorization: xxxxxxxxxxxxxxx",
"Accept: application/json."
"Content-Type: multipart/form-data"
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
The problem is that the GET method response arrives before the API has time to process it. Therefore, when I print the response I print WAITING FOR RESPONSE and not whether it went ok or failed.
What can I do to print the ok or fail and not the WAITING FOR RESPONSE?
Thank you very much!

Requesting a cURL GET Request in PHP outputs garbage

I'm trying to build a Connector to Dynamics 365 Business Central but I'm having problems getting the data. Please help me figure out why when I send a GET request using cURL and PHP, it produces the following output:
�S[O�0�+(��&��qB��i�t�F/���=�ا��Ďb�}N�"&�M�����������8�0% �;
Here is my code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.businesscentral.dynamics.com/{tenantID}/customers/?$filter=displayName%20eq%20'Shawn%20Test'",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: {Auth Code}"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
It seems like a character encoding issue, or maybe you are receiving binary data.
What is this endpoint supposed to return? Check the response headers, it might give you a clue.
This is an encoding problem, try to remove CURLOPT_ENCODING line from your request or try to choose different encoding from your browser

Categories