3

I'm trying to get data onto my website by parsing data from a JSON format. The URL is http://api.bfhstats.com/api/onlinePlayers and I'm trying to output for example the currently players online on PC.

Here's the current code I have:

<?$json = file_get_contents("http://api.bfhstats.com/api/onlinePlayers");
$data = json_decode($jsondata, true);
echo $data->pc->peak24;?>

I thought this would work, however it's not displaying anything. I am very new to parsing JSON data so if someone could explain what I'm doing wrong that would be brilliant.

1
  • 1
    See one error in your code: $json and $jsondata Commented Mar 25, 2015 at 20:51

3 Answers 3

2

You are missing the foreach cycle to fetch the two dimensional array $data:

<?php
$json = file_get_contents("http://api.bfhstats.com/api/onlinePlayers");
$data=array();
$data = json_decode($json, true);
//print_r ($data);
foreach ($data as $pc) { 
    echo $pc["peak24"]."<br>";
}
?>

Check the $json and $jsondata that have different name but should be the same.

Sign up to request clarification or add additional context in comments.

Comments

1

change:

$data = json_decode($jsondata, true);

to

$data = json_decode($json, true);

Also, json_decode returns an array so use:

echo $data['pc']['peak24'];

to access the data.

2 Comments

Just to clarify, json_decode returns an associative array when the second parameter is set to true. If he changes it to false (or leaves it as default) he can use his existing code.
Changed it now, however nothing is displaying. I think it's the format of which i've called the json objects. Thanks for the fast response
1

You first call the variable $json but then use $jsondata in json_decode.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.