Retrieving string value JSON

2

I have a PHP application that returns me a string Json :

$cep = $_POST['cep'];

$token = '';
$url = 'http://www.cepaberto.com/api/v2/ceps.json?cep=' . $cep;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Token token="' . $token . '"'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
echo $output;

I would like to know how to get the value of the string that is returned

  

{"altitude":14.3,"bairro":"Santa Inês","cep":"68901487","latitude":"0.0355735","longitude":"-51.070535","logradouro":"Passarela Acelino de Leão","cidade":"Macapá","ddd":96,"ibge":"1600303","estado":"AP"}

    
asked by anonymous 25.07.2017 / 22:15

2 answers

4

Use json_decode to transform into a array associative , example

<?php

$cep = $_POST['cep'];

$token = '';
$url = 'http://www.cepaberto.com/api/v2/ceps.json?cep=' . $cep;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Token token="' . $token . '"'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);


$array = json_decode($output, true);

echo $array['altitude'];
echo $array['bairro'];
echo $array['cep'];
echo $array['latitude'];
echo $array['longitude'];
echo $array['logradouro'];
echo $array['cidade'];
echo $array['ddd'];
echo $array['ibge'];
echo $array['estado'];

and as shown go to each key and print the result.

25.07.2017 / 22:28
3

In PHP, the json_encode and json_decode functions are used to work with json. In your case, json_decode will transform the received text into an array, making it easier to manipulate:

$array = json_decode($output);
    
25.07.2017 / 22:28