How to display the values of a JSON via PHP?

1

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

    $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? Home Ex.
echo "Bairro: $bairro";
echo "Logradouro: $logradouro";
echo "CEP: $cep";
echo "UF: $uf";
echo "Localidade: $localidade";
Result: Home Neighborhood: Jangurussu Home Street: Street 22 Home CEP: 60876470 Home UF: CE Home Location: Fortaleza     
asked by anonymous 02.01.2015 / 23:30

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" 

}

so you can use echo to print those values. If you want to do in a loop you can do this:

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

Example: link

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

For example:

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

And then you can do this:

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