2013-08-18 65 views
1

這裏是我的PHP腳本:PHP未定義抵消:1

<?php 
$address = htmlentities(strtolower(Config::get('aac.ip'))); 
$port = Config::get('aac.port'); 

@$sock = fsockopen ($address, $port, $errno, $errstr, 1); 
if(!$sock) echo '<small class="muted"><strong>Server status:</strong></small> <span class="label label-important">OFFLINE</span><br />'; else { 
$info = chr(6).chr(0).chr(255).chr(255).'info'; 
fwrite($sock, $info); 
$data=''; 
while (!feof($sock))$data .= fgets($sock, 1024); 
fclose($sock); 

// if needed 
// var_dump($data); 


preg_match('/players online="(\d+)" max="(\d+)"/', $data, $matches); 
$players = ''.$matches[1].'/'.$matches[2]; 
preg_match('/uptime="(\d+)"/', $data, $matches); 
$h = floor($matches[1]/3600); 
$m = floor(($matches[1] - $h*3600)/60); 
$uptime = ''.$h.'h '.$m.'m'; 
preg_match('/monsters total="(\d+)"/', $data, $matches); 
$monsters = ''.$matches[1]; 
preg_match('#<motd>(.*?)</motd>#s', $data, $matches); 
$motd = ''.$matches[1]; 
preg_match('/npcs total="(\d+)"/', $data, $matches); 
$npcs = ''.$matches[1]; 

if(empty($players) or $players == "/") $players = "???/???"; 
if(empty($uptime)) $uptime = "???"; 
if(empty($monsters)) $monsters = "???"; 
if(empty($motd)) $motd = "???"; 

echo " 
<small class='muted'><strong>Server status:</strong></small> <span class='label label-success'>ONLINE</span><br /> 
<small class='muted'><strong>Players:</strong> $players</small><br /> 
<small class='muted'><strong>Uptime:</strong> $uptime</small><br /> 
<small class='muted'><strong>Monsters:</strong> $monsters</small><br /> 
<small class='muted'><strong>MOTD:</strong> $motd</small><br /> 
$npcs 
"; 
} 

?> 

$npcs變量返回一個錯誤Undefined offset: 1。我試圖用很多方式解決這個問題,但都沒有成功。此外,這裏是var_dump數據:

string '<?xml version="1.0"?> 
<tsqp version="1.0"><serverinfo uptime="33360" ip="127.0.0.1" servername="Forgotten" port="7171" location="Europe" url="http://otland.net/" server="The Forgotten Server" version="0.2.15" client="9.86"/><owner name="" email="@otland.net"/><players online="2" max="1000" peak="2"/><monsters total="636"/><map name="forgotten" author="Komic" width="1000" height="1000"/><motd>Welcome to the Forgotten Server!</motd></tsqp> 
' (length=442) 

我試圖檢索信息。另外,我能檢索服務器名稱,位置和類似的東西嗎?我沒有經歷過很多。 :P當您嘗試使用例如不存在的索引來訪問數組項PHP

+0

'$ npcs =''。$ matches [1];'如果這是返回錯誤的行,意味着上面的'preg_match()'可能找不到任何匹配結果 – JLewkovich

+0

''npcs' $ data'因此'$ matches'與'$ npcs'一致是空的。 –

+0

而不是測試$玩家/ $怪物/等。測試你的preg_match比較好。例如:'if(preg_match(........)){/ *做某事* /} else {/ *做其他事情* /}' –

回答

9

一個未定義的偏移誤差發生,讓我們說我有以下幾點:

<?php 
$fruit = array('apple', 'orange', 'pear'); 
echo $fruit[0]; // apple 
echo $fruit[1]; // orange 
echo $fruit[3]; // Undefined offset:3 

在上面的例子中,數組有三個項目。這些項目的索引是0,1,2。沒有索引爲3的項目。因此,當我嘗試訪問$ fruit [3]時發生錯誤。

在您的具體情況下,沒有$匹配[1]。您應該排查preg_match()調用,並查看您的模式是否返回任何匹配。

作爲一個更普遍的建議,我建議你在嘗試訪問它之前檢查一個數組鍵的存在。