Recovering string JSON value

Asked

Viewed 145 times

2

I have an app PHP 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"}

2 answers

4


Utilize json_decode to turn 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 demonstrated access each key and print the result.

Reference:

  • 2

    Thank you so much! You helped me, it was exactly what I needed!

3

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

$array = json_decode($output);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.