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


PHP - using a line from a text file in an IF statement

我正在尝试让一个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 行的修剪功能是缺少的。

您的问题是文件的每一行都以 '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";
}

第一个问题是如果你回显$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";
}
?>

输出'&activeGame=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";
}