user985952 user985952 - 2 years ago 50
PHP Question

How do I consume this JSON response?

I'm trying to append some JSON I'm getting from an API response to an email and I wish to output the JSON into a HTML table. The problem is the JSON response doesn't look like anything I've worked with before.

$vs_getClickPath = wp_remote_get('url');
$clickPath_body = wp_remote_retrieve_body( $vs_getClickPath );
$notification['message'] .= $clickPath_body;

This gives me the below:

["date\/time", "page name visited", "city", "region", "country", "company name\/isp", "identity", "search\/referral"],
["2016-05-17 10:56:05", "Home Page", "Buffalo", "New York", "United States", "I-evolve Technology Services", "", ""]

All of the keys come first in one array then in another array the values show up. Trying to work with indexes just gets the individual characters, foreach doesn't work. I've tried
, but it doesn't output anything with

Is there anyway I will be able to loop through this and output the data into a HTML table? The first array would be the table headers and every array after that would be the table rows.

Answer Source

I used json_decode($str, true) and it returned an array that can be worked with:

$str = '[["date\/time","page name visited","city","region","country","company name\/isp","identity","search\/referral"],["2016-05-17 10:56:05","Home Page","Buffalo","New York","United States","I-evolve Technology Services","",""]]';
$json = json_decode($str, true);
echo '<pre>';


    [0] => Array
            [0] => date/time
            [1] => page name visited
            [2] => city
            [3] => region
            [4] => country
            [5] => company name/isp
            [6] => identity
            [7] => search/referral

    [1] => Array
            [0] => 2016-05-17 10:56:05
            [1] => Home Page
            [2] => Buffalo
            [3] => New York
            [4] => United States
            [5] => I-evolve Technology Services
            [6] => 
            [7] => 


Setting true in the call to json_decode() makes the function return an array. If you do not want an array, you can return an abject by leaving the option out of the call.

PHP's json_decode()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download