文件存在-空条件测试的PHP测试产生不一致的结果



我正在提取一个XML文件并执行各种数据处理。我将一个元素(没有数据)分配给一个变量,并测试该变量是否为空。这个测试是错误的。不知道为什么,我直接测试了这个元素,结果通过了测试。我对此感到困惑,把这个变量放在几个条件下,看看我在处理什么。这让我感到困惑,因为结果对我来说似乎完全不一致。我输入的代码如下:

$xmldata = simplexml_load_file('data.xml');
$picture = $person->picturefile;       <--picturefile is empty
if (!empty($person->picturefile)) {
    echo "picture is not empty";
    } else {
    echo "picture is empty";
    }
if (!empty($picture)) {
    echo "picture is not empty";
    } else {
    echo "picture is empty";
    }
$tempfile = "members/$picture";
if (file_exists($tempfile)) {
   echo "<div class=mgridimg><img src=$tempfile></div>";
}

xml路径的测试产生一个假条件(图片为空),但变量的测试产生了一个真条件(图片不为空)
我对这个变量进行了strlen测试,结果显示strlen=0。

从xml文件中,$picture在填充时具有文件名。同样令人困惑的是,尽管$picture是空的,但file_exists测试通过了true。我还验证了在上面的测试中,$tempfile包含一个值"members/"。我无法理解变量的空测试或file_exists测试。我可以围绕这一点进行编码,但我想知道为什么我看到的是我所看到的。任何见解都值得赞赏。

对于第一种情况,我认为这几乎不可能是真的。他们应该是平等的。你试过修剪吗?

对于file_exists函数,如果您不想在dir上为true,则应该检查!is_dir()

例如:

var_dump(file_exists('New Folder/'));
var_dump(file_exists('New Folder/') && !is_dir('New Folder/'));
var_dump(file_exists('New Folder/New Text Document.txt') && !is_dir('New Folder/New Text Document.txt'));

输出:

boolean true
boolean false
boolean true

最新更新