无限循环读取文本文件



我正在WordPress中制作一个自定义主题。现在在主题文件夹中是另一个名为"php"的文件夹,其中包含一个文本文件,让我们说"names.txt"。现在我想做的是从"php"文件夹中读取文本文件。我的索引中有以下代码.php:

<?php
 $file = fopen("/php/names.txt","r");
 while(! feof($file))
 {
 echo fgets($file). "<br />";
 }
 fclose($file);
 ?>

但是我的网页陷入了无限循环,尽管文件不存在,但存在文件不存在的错误。急需帮助。更新:我尝试在一个单独的php.file中运行上面的代码,我将其与"names.txt"文件放在同一个目录中,它读取数据。

更新 [已解决]:

<?php
$location = get_template_directory() . "/php/admin.txt";
if ( file_exists( $location )) {
$file = fopen($location, "r");
while(!feof( $file )) {
    echo fgets($file). "<br />";
} 
fclose($file);
}
else
{echo "no file.";}
?>

像魔术一样工作,多亏了@MackieeE

首先使用

file_exists()对文件进行更好的检查系统:

if ( !file_exists( "/php/names.txt", "r" )) 
   echo "File not found";

然后让我们看看你是如何调用文件的 - 它可能只是找不到它!目前,您的WordPress脚本可能从主题文件夹中调用它,如下所示:

   --> root
      --> wp-content
        --> themes
          --> yourtheme
            --> php
              --> names.txt

尽管如前所述,当前脚本正在以下位置查找它:

  --> root
    --> php
      --> names.txt

因为/php/内的起始斜杠

确保将名称.txt放在正确的位置,您可以使用Wordpress的预定义变量get_template_directory()或PHP的$_SERVER["DOCUMENT_ROOT"]来确保在需要时指向正确的文件夹:

 $location = get_template_directory() . "php/names.txt";
 if ( file_exists( $location )) {
    $file = fopen($location, "r");
    while(!feof( $file )) {
        echo fgets($file). "<br />";
    } 
    fclose($file);
 }