2012-10-01 135 views
0

我有一个名为tracker.txt的文件,其中包含3行。 txt文件是这样的:http://tracker.cpcheats.co/rookie/tracker.txt。我使用的file_get_contents和爆炸返回数组的每一行,像这样:PHP file_get_contents和爆炸与if语句无法正常工作

$read = file_get_contents('tracker.txt'); 
$filed = explode("\n",$read); 
$status = $filed[0]; 
$server = $filed[1]; 
$room = $filed[2]; 

我再有一个if语句,这里的条件是如果tracker.txt($状态)的第一行是“发现',那么它会将第二行和第三行写出到图像上。它不起作用。

if ($status == 'found') { 
//write out the server room and language (with shadow) 
imagettftext($im, 15, 0, 140, 80, $white, $font, $server); 
imagettftext($im, 15, 0, 139, 79, $black, $font, $server); 
imagettftext($im, 15, 0, 140, 105, $white, $font, $room); 
imagettftext($im, 15, 0, 139, 104, $black, $font, $room); 
} 

奇怪的是,如果我只是打印出$地位,$服务器和$房间没有if语句,它工作正常,并dispays正确的线路。为什么它不符合条件?因为,我确定http://tracker.cpcheats.co/rookie/tracker.txt的第一行是'找到'的。

+0

该文件是否使用DOS风格的换行符(http://en.wikipedia.org/wiki/Newline)?即在你爆炸的'\ n'之前的每行末尾是否有'\ r'字符? – rjz

+0

就在我给你的第一块代码之前,我有这个。 '$ file = fopen(“tracker.txt”,“w”); echo fwrite($ file,“found \ n(EN)Avalanche \ nIce Berg”); fclose($ file);' – Penian4

+0

PHP也有['file()'](http://php.net/file)函数,它读取文件并返回数组中的所有行。 – mario

回答

2

你应该尝试使用trim删除空白空格

$string = file_get_contents("http://tracker.cpcheats.co/rookie/tracker.txt"); 
$string = explode("\n", $string); 
list($status, $server, $room) = array_map("trim", $string); 

之前修剪

array 
    0 => string 'found 
' (length=6) 
    1 => string ' (EN) Avalanche 
' (length=16) 
    2 => string 'Ice Berg' (length=8) 

//后修剪

array 
    0 => string 'found' (length=5) 
    1 => string '(EN) Avalanche' (length=14) 
    2 => string 'Ice Berg' (length=8) 

你能看到,长度为$status是不同的length=6length=5分别

您也可以只做

if (trim($status) == 'found') { 
    // .... 
} 
+0

谢谢,完美无缺! – Penian4

+0

@ Penian4欢迎您 – Baba

0

看起来你有一个额外的\ r。此作品:

if ($status == "found\r"){ 
    ... 
}