user985952 user985952 - 6 months ago 8
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
json_decode
, but it doesn't output anything with
print_r
or
var_dump
.

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

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>';
print_r($json);

returns

Array
(
    [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()