Consume a Json Web Service with PHP

1

Good morning how are you, I hope very well, I would like you to help me a bit in a matter of consuming a web service through a URL that should return a result in JSON, something that does not work and also in the result It just throws me weird symbols, this thing is messing me up a bit.

Here's how I'm doing it, thank you very much.

$ apiUrl = ' link ';

if(ini_get('allow_url_fopen')){
    $json = file_get_contents($apiUrl);
} else{
    $curl = curl_init($apiUrl);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $json = curl_exec($curl);
    print($json);
    curl_close($curl);
}
    
asked by Alonsso 06.02.2018 в 15:36
source

1 answer

1

You have to clean the data, with curl_setopt($curl, CURLOPT_ENCODING ,""); .

According to the PHP Manual :

  

Content of the "Accept-Encoding:" value in the header. This allows   decode the answer . The coding formats available   they are "identity", "deflate", and "gzip". If the value is sent empty, "",   All types of condificación supported will be sent.

I did a test with this code:

$apiUrl = 'http://api.cne.cl/v3/combustibles/calefaccion/estaciones?token=PT33JekNhp&distribuidor=Copec';
$curl = curl_init($apiUrl);
curl_setopt($curl, CURLOPT_ENCODING ,"");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($curl);
print($json);
curl_close($curl);

And show me the data well:

{
    "estado": "OK",
    "descripcion": "Token Valida",
    "data": [{
                "id": "co110101",
                "fecha_hora_actualizacion": "2018-02-01 09:57:15",
                "razon_social": "BORRADO POR CONFIDENCIALIDAD",
                "direccion_calle": "BORRADO",
                "direccion_numero": "BORRADO",
                "id_comuna": "01101",
                "nombre_comuna": "Iquique",
                "id_region": "01",
                "nombre_region": "Tarapac\u00e1",
                "horario_atencion": "24 horas",
 .....
    
answered by 06.02.2018 в 16:27