使用if语句,PHP file_get_contents和explode无法正常工作

问题描述:

I have a file called tracker.txt that contains 3 lines. The txt file is this: http://tracker.cpcheats.co/rookie/tracker.txt. I am using file_get_contents and explode to return each line of the array, like so:

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

I then have an if statement, where the condition is if the first line of tracker.txt ($status) is 'found', then it will write out the second and third line onto the image. It doesn't work.

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);
}

The odd thing is, if I just print out $status, $server and $room without the if statement, it works fine and dispays the correct lines. Why isn't it working with the condition? Because, I'm sure the first line of http://tracker.cpcheats.co/rookie/tracker.txt is 'found'.

You should try using trim to remove empty white space

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

Before trim

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

// After Trim

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

Can you see that the length is of $status is different length=6 and length=5 respectively

You can also just do

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

Looks like you have an extra . This works:

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