2012-10-01 133 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"){ 
    ... 
}