2

currently i am using the below code to get a file from a site which tells me the current server status of a game server. the file is in plain text format and out puts the following depending on server status:

ouput:

{ "state": "online", "numonline": "185" }

or

{ "state": "offline" } 

or

{ "state": "error" }

file get code:

<?php 
   $value=file_get_contents('http:/example.com/server_state.aspx');
      echo $value;
?>

I would like to turn the 'state' and 'numonline' into their own variables so i could output them using a if, like:

<?php 
$content=file_get_contents('http://example.com/server_state.aspx');

$state  <--- what i dont know how to make
$online <--- what i dont know how to make

if ($state == online) {     
   echo "Server: $state , Online: $online"; 
}  else {
   echo "Server: Offline";
)       

?>

but i have no idea how to turn the 'state' and 'numonline' from the plain text into a variable of their own ($state and $online), how would i go about doing this?

1

3 Answers 3

4

Your data is JSON. Use json_decode to parse it into a usable form:

$data = json_decode(file_get_contents('http:/example.com/server_state.aspx'));

if (!$data) {
    die("Something went wrong when reading or parsing the data");
}

switch ($data->state) {
    case 'online':
        // e.g. echo $data->numonline
    case 'offline':
        // ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use json_decode function:

$value = '{ "state": "online", "numonline": "185" }';
$json = json_decode($value, true);
print_r($json);

if ($json['state'] == 'online') {     
   echo "Server: " . $json['state'] . " , Online: " . $json['numonline']; 
}  else {
   echo "Server: Offline";
}

Output:

Array
(
    [state] => online
    [numonline] => 185
)

Comments

1

I would like to turn the 'state' and 'numonline' into their own variables:

Maybe you are looking for extract,

Example:

$value = '{ "state": "online", "numonline": "185" }';
$json = json_decode($value, true);
extract($json);

//now $state is 'online' and $numonline is 185

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.