从纯文本获取文件的php变量

时间:2013-05-28 11:50:03

标签: php

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

输出中:

{ "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),我将如何做到这一点?

3 个答案:

答案 0 :(得分: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':
        // ...
}

答案 1 :(得分: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
)

答案 2 :(得分: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