How to display the values of a JSON via PHP?

Asked

Viewed 522 times

1

How can I display the values of a JSON via echo in PHP, I am using the code below to receive the JSON from the Post Office website

    $json_file = file_get_contents("http://cep.correiocontrol.com.br/$cep.json");
$json_str = json_decode($json_file, true); //echo "$json_str";
This JSON has the following values:
{"bairro": "Jangurussu", "logradouro": "Rua 22", "cep": "60876470", "uf": "CE", "localidade": "Fortaleza"}
Is there any way I can use echo to display these values?
Ex.
echo "Bairro: $bairro";
echo "Logradouro: $logradouro";
echo "CEP: $cep";
echo "UF: $uf";
echo "Localidade: $localidade";
Upshot:
District: Jangurussu
Patio: Street 22
CEP:60876470
UF:CE
Locality:

1 answer

3


After you use $json_str = json_decode($json_file, true); your array (now associative) will look like this:

array(5) 
{ 

    ["bairro"]=> string(10) "Jangurussu" 
    ["logradouro"]=> string(6) "Rua 22" 
    ["cep"]=> string(8) "60876470" 
    ["uf"]=> string(2) "CE" 
    ["localidade"]=> string(9) "Fortaleza" 

}

then you can use echo to print those values. If you want to do it inside a loop you can do it like this:

foreach ($json_str as $key => $value) {
    echo "$key: $value<br />\n"; // aqui podes colocar mais HTML se quiseres
}

Example: http://ideone.com/6kXUT2

If you want to map these keys/Keys then I suggest you have another array to give the name with high box.

For example:

$titulos = array("bairro"=>"Bairro", "logradouro"=>"Logradouro", "cep"=>"CEP", "uf"=>"UF",  "localidade"=>"Localidade");

and then you can do it like this:

foreach ($json_str as $key => $value) {
    echo "$titulos[$key]: $value<br />\n"; // aqui podes colocar mais HTML se quiseres
}

Browser other questions tagged

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