JavaScript中的奇怪问号

时间:2014-07-13 20:27:26

标签: javascript php minecraft

我正在尝试创建一个脚本,ping我的Minecraft服务器以检查有多少玩家在线,但由于某种原因,问号正在显示,这使整个网站看起来像垃圾。这是我的PHP文件。

<script>
    function setOnline(online,max) {
        var on = online;
        var mx = max;

        var main = document.getElementById('status_main');
        main.className = "panel panel-success server-status";

        var title = document.getElementById('status_title');
        title.innerHTML = "Online";

        var body = document.getElementById('status_body');
        body.innerHTML = on + "/" + mx + " Players Online";
    }
</script>

<script>
    function setOffline() {
        var bar = document.getElementById('status');
        bar.className = "panel panel-danger server-status";
        bar.text = "Offline";
    }
</script>
<?php
$host = "localhost"; //IP/host of Minecraft server
$port = 25565; //Minecraft server port, not query port
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); //Create the socket
$connected = socket_connect($socket, $host, $port); //Try and connect using the info provided above
 if (!$connected)
    die(); //No connection could be established

socket_send($socket, "\xFE\x01", 2, 0); //Send the server list ping request (two bytes)
$retVal = socket_recv($socket, &$data, 1024, 0); //Get the info and store it in $data
socket_close($socket); //Close socket

if ($retVal != false && substr($data, 0, 1) == "\xFF") //Ensure we're getting a kick message as expected
{
    $data = substr($data, 9); //Remove packet, length and starting characters
    $data = explode("\x00\x00", $data); //0000 separated info
    $protocolVersion = $data[0]; //Get it all into separate variables
    $serverVersion = $data[1];
    $motd = $data[2];
    $playersOnline = $data[3];
    $playersMax = $data[4];
    echo ("<script>setOnline('$playersOnline','$playersMax');</script>");
}
else
{
    die();
}
?>

以下是调用时的结果: http://cl.ly/image/3o2f3P121q0m

如何摆脱问号?

1 个答案:

答案 0 :(得分:0)

这可能是一个字符集问题。信息未按编码方式显示。

您可以var_dump $ data查看其内容类型。


这只是一个假设:实际编码是ISO-8859-1,但它被解释为UTF-8(或UTF-16)。

要使浏览器使用正确的编码,您可以添加HTTP标头:

header("Content-Type: text/plain; charset=ISO-8859-1");

或使用元标记。