Question

I am trying to get json data from the Statcounter API.

I have the following:

$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];

I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.

Here are the first couple lines of the unformatted json it is giving me.

This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.

http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514

{"@attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar 

Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!

Thank you for your help.

Was it helpful?

Solution

Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:

echo $data['sc_data'][0]['log_visits'];

The code above will access the first element of the array sc_data and print the value of log_visits

When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].

The elements of the array can be any valid value, i.e.

  • string
  • number
  • object
  • array
  • true
  • false
  • null

In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top