2

目前我正在使用以下代码从网站获取文件,该文件告诉我游戏服务器的当前服务器状态。该文件为纯文本格式,并根据服务器状态输出以下内容:

输出:

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

或者

{ "state": "offline" } 

或者

{ "state": "error" }

文件获取代码:

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

我想将 'state' 和 'numonline' 变成它们自己的变量,这样我就可以使用 if 来输出它们,例如:

<?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";
)       

?>

但我不知道如何将纯文本中的“状态”和“numonline”转换为它们自己的变量($state 和 $online),我该怎么做呢?

4

3 回答 3

4

您的数据是JSON。用于json_decode将其解析为可用的形式:

$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':
        // ...
}
于 2013-05-28T11:51:52.623 回答
1

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

也许你正在寻找extract

例子:

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

//now $state is 'online' and $numonline is 185
于 2013-05-28T11:56:56.417 回答
1

使用json_decode函数:

$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";
}

输出:

Array
(
    [state] => online
    [numonline] => 185
)
于 2013-05-28T11:52:26.987 回答