从纯文本获取文件创建PHP变量


make php variable from plain text get file

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

输出:

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

但是我不知道如何将'state'和'numonline'从纯文本转换为自己的变量($state和$online),我该怎么做呢?

您的数据是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':
        // ...
}

使用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
)

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