1

我正在 WordPress 中制作自定义主题。现在主题文件夹内是另一个名为“php”的文件夹,其中包含一个文本文件,比如说“names.txt”。现在我要做的是从“php”文件夹中读取文本文件。我的 index.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

4

1 回答 1

1

首先为文件做一个更好的检查系统,使用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/

确保将 names.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);
 }
于 2013-12-21T18:38:45.743 回答