PHP - 使用IF语句中的文本文件中的一行

时间:2016-02-17 19:31:47

标签: php

我正在尝试从文本文件中读取特定行的PHP文件,然后在if语句的字符串比较中使用该行。
文本字段中的第二行将始终具有两个不同值中的一个。 &activeGame=0&activeGame=1

文本文件:

boardarray=["NV", "SB", "VB", "NV"]  
&activeGame=1  
&activePlayer=V  

PHP文件:

$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks

if ($line[1] == "&activeGame=1") {
    echo "The game is active";
} else {
    echo "The game is not active";
}

由于echo $line[1]输出&activeGame=1,我知道PHP脚本可以从文本文件中读取数据。
问题是if函数将回显"The game is not active"而我无法弄清楚原因。

修改
解决方案:

$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks

if (trim($line[1]) == "&activeGame=1") { 
    echo "The game is active";
} else {
    echo "The game is not active";
}

第5行的修剪功能是缺失的。

3 个答案:

答案 0 :(得分:6)

您的问题是文件的每一行都以\n结尾。

如果你var_dump($line[1])而不是回应它,你可以看到它。

&activeGame=1的真正价值是&activeGame=1\n。 这绝对不等于&activeGame=1

因此,在比较之前 - 使用trim函数:

$theFile = "test.txt";
$line = file($theFile);
echo $line[1]; //This will output "&activeGame=1" without quotation marks

$line_one = trim($line[1]);
if ($line_one == "&activeGame=1") {
    echo "The game is active";
} else {
    echo "The game is not active";
}

答案 1 :(得分:1)

我会以这种方式使用parse_str,即使该行上有更多变量,您也可以始终获得该值。 http://php.net/manual/en/function.parse-str.php

$theFile = "test.txt";
$line = file($theFile);
parse_str($line[1],$output);

if ($output['activeGame'] == 1) {
    echo "The game is active";
} else {
    echo "The game is not active";
}

答案 2 :(得分:1)

第一个问题如果你回显$ line [1]那么它的值是“& activeGame = 1”(注意结尾处的空格。并且是最佳解决方案能为您提供所需输出的代码如下所示

<?php
$theFile = "test.txt";
$line = file($theFile);
echo trim($line[1]); //This will output "&activeGame=1" without     quotation marks

$a=trim($line[1]);

$truestr="&activeGame=1";


if ($a == $truestr) {
    echo "The game is active";
} else {
    echo "The game is not active";
}
?>

OUTPUT '&amp; activeGame = 1'游戏正在激活