Read json output in Php

Asked

Viewed 74 times

1

How do I read this output?

curl http://127.0.0.1:8775/scan/3730f9794bffb6aa                                                                                       /log
{
    "log": [
        {
            "message": "testing connection to the target URL",
            "level": "INFO",
            "time": "10:24:05"
        },
        {
            "message": "checking if the target is protected by some kind of WAF/                                                                                        IPS/IDS",
            "level": "INFO",
            "time": "10:24:07"
        },

I tried it, but it didn’t work

<?php
$json_file = file_get_contents("http://127.0.0.1:8775/scan/3730f4794bffb6fb/log");   
$json_str = json_decode($json_file, true);
$itens = $json_str['nodes'];

foreach ( $itens as $e ) 
    { echo $e['"message"']."<br>"; } 

php?>
  • 3

    It seems that in your json does not exist 'nodes', maybe the right thing is $itens = $json_str['log']; and this also feels wrong ['"message"'], the correct should be $e['message']

1 answer

1

Whereas your JSON structure is OK, cfme example below.

{
    "log": {
        "1": {
            "message": "testing connection to the target URL",
            "level": "INFO",
            "time": "10:24:05"
        },
        "2": {
            "message": "checking if the target is protected by some kind of WAF/ IPS/IDS",
            "level": "INFO",
            "time": "10:24:07"
        }
    }
}

That would be the PHP code

/** Substitua essa chamada pela recuperação do arquivo remoto **/
    $json_str = '{ "log": { "1": { "message": "testing connection to the target URL", "level": "INFO", "time": "10:24:05" }, "2": { "message": "checking if the target is protected by some kind of WAF/ IPS/IDS", "level": "INFO", "time": "10:24:07" }  } }';

    $obj = json_decode($json_str);

    /** use um laço aninhado */
    foreach ($obj as $objeto){

        /*lendo então os atributos de cada item do objeto */
        foreach ($objeto as $item){

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

The following output will be generated:

Mensagem: testing connection to the target URL - Nível: INFO
Mensagem: checking if the target is protected by some kind of WAF/ IPS/IDS - Nível: INFO

Browser other questions tagged

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