1

WordPressでカスタムテーマを作っています。テーマ フォルダー内には、"names.txt" としましょう。ここでやりたいことは、「php」フォルダーからテキスト ファイルを読み取ることです。index.php に次のコードがあります。

<?php

 $file = fopen("/php/names.txt","r");

 while(! feof($file))
 {
 echo fgets($file). "<br />";
 }

 fclose($file);

 ?>

しかし、私の Web ページは無限ループに陥っており、ファイルは存在するのに存在しないというエラーが表示されます。ひどく助けが必要です。更新:「names.txt」ファイルと同じディレクトリに配置した別のphp.fileで上記のコードを実行してみましたが、データが読み取られました。

更新[解決済み]:

<?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.";}
?>

@MackieE のおかげで魔法のように機能します

4

1 に答える 1

1

Start off by doing a better check system for the file, using file_exists():

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

Then let's look on how you're calling the file from - it's probably just unable to find it! Currently, your WordPress script is probably calling it from the themes folder as below:

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

Although as mentioned, the current script is looking for it in:

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

Because of the starting slash within your /php/

Make sure you're placing your names.txt in the correct location, you can use Wordpress'es pre-defined variables get_template_directory() or PHP's $_SERVER["DOCUMENT_ROOT"] to make sure you point to the correct folder if need be:

 $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 に答える