Net
Net

Reputation: 13

How to display a JSON object with php and cURL?

I'm very new to php (I know next to nothing, in fact) and I'm trying to display an object from a JSON string on a website (probably not the right terminology but you know... I'm new...). Here's the cURL code I'm using:

$url="http://mc.gl:8081/?JSONSERVER=lobby";
//  Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);

Then I have this that's supposed to do something (I really dont understand it)

// Will dump a beauty json :3
var_dump(json_decode($result));

Annnnnddd.... what do I do next? I've done a lot of googling and nothing seems to work. Here's the string that I should be getting:

{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}

and I want to echo "playeramount".

Any help would be greatly appreciated! Thanks so much!

Upvotes: 0

Views: 4298

Answers (2)

Amal
Amal

Reputation: 76636

The var_dump() function in PHP is used to display structured information about variables. It is usually used for debugging and has nothing to do with the JSON decode.

In this case, the $result variable will contain the JSON string you need. To decode it, use PHP's built-in function json_decode():

$json = json_decode($result); // decode JSON string into an object

Note: It's also possible to get an associative array by passing TRUE as the second parameter to json_decode().

Once you have the object, you can traverse it to get the required value:

echo $json->lobby->playeramount;

Demo!

Upvotes: 2

If you want to access the result as an associative array, you can do like this too [By passing a true flag in the json_decode() function]

<?php
$str='{"lobby":{"playeramount":1,"players":{"MisterErwin":"MisterErwin"}},"API-Version":"1","return":true}';
$str=json_decode($str,true); // Setting the true flag 
echo $str['lobby']['playeramount']; //Outputs 1

Upvotes: 1

Related Questions