How to Read this json with PHP

2

How do I read this JSON file with PHP.

I tried this way, but it does not work.

<?php

    $json_str = '{
    "numero":"1000",
    "log": {
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    },
    "responsavel": {
        "nome":"Responsavel teste"
    }
}';

    $obj = json_decode($json_str);


    foreach ($obj as $objeto){

        echo "numero: ".$objeto->numero;

        foreach ($objeto as $item){

            echo "Mensagem: ".$item->message. " - ";
            echo "Nível: ".$item->level. "</br>";
        }

        foreach ($objeto as $responsavel){

            echo "NOME: ".$item->nome;

        }

    }


?>
    
asked by anonymous 23.09.2017 / 16:15

2 answers

4

The json that presented has no arrays is all objects, so it will not make sense to use foreach to go through.

To access the fields you are trying to access in your code you can do this:

echo "numero: ".$obj->numero;
echo "Mensagem: ".$obj->log->message. " - ";
echo "Nível: ".$obj->log->level. "</br>";
echo "NOME: ".$obj->responsavel->nome;

Example on Ideone

In order to be able to use the foreachs you have in the code, json had to look like this:

[{
    "numero": "1000",
    "log": [{
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    }],
    "responsavel": [{
        "nome": "Responsavel teste"
    }]
}]

Notice how you now have [ and ] in each to indicate that it is an array of objects, which we can now walk with foreach .

The code to go through has also slightly adjusted that it had some errors:

$obj = json_decode($json_str);

foreach ($obj as $objeto){

    echo "numero: ".$objeto->numero;

    foreach ($objeto->log as $item){ //faltava aqui $objeto->log

        echo "Mensagem: ".$item->message. " - ";
        echo "Nível: ".$item->level. "</br>";
    }

    foreach ($objeto->responsavel as $responsavel){ //faltava aqui $objeto->responsavel

        echo "NOME: ".$responsavel->nome;

    }

}

See this latest version also in Ideone

    
23.09.2017 / 16:25
1

By default json_decode returns a stdClass and for your access it is not possible to use foreach .

On the other hand you can json_decode return an array, which in turn is iterable. In that particular file, it might not be worth it and use as a suggested object is simpler:

$json_str = '{
    "numero":"1000",
    "log": {
        "message": "testing connection to the target URL",
        "level": "INFO",
        "time": "10:24:05"
    },
    "responsavel": {
        "nome":"Responsavel teste"
    }
}';

var_dump(json_decode($json_str, true);
    
23.09.2017 / 20:34