0

以下のスクリプトでは、$baseフォルダー内のフォルダーとファイルを反復処理しようとしています。単一レベルの子フォルダーが含まれ、それぞれに多数の.txtファイルが含まれている(サブフォルダーは含まれていない)と思います。

以下のコメントの要素を参照する方法を理解する必要があります...

どんな助けでも大歓迎です。私はこれをまとめるのに本当に近いです:-)

$base = dirname(__FILE__).'/widgets/';
$rdi = new RecursiveDirectoryIterator($base);
foreach(new RecursiveIteratorIterator($rdi) as $files_widgets) 
    {
     if ($files_widgets->isFile()) 
         {
            $file_name_widget = $files_widgets->getFilename(); //what is the filename of the current el?
            $widget_text = file_get_contents(???); //How do I reference the file here to obtain its contents?
            $sidebar_id = $files_widgets->getBasename(); //what is the file's parent directory name?
        }
    }
4

1 に答える 1

2
//How do I reference the file here to obtain its contents?
    $widget_text = file_get_contents(???); 

$files_widgetsSplFileInfoであるため、ファイルの内容を取得するためのいくつかのオプションがあります。

最も簡単な方法はfile_get_contents、今と同じようにを使用することです。パスとファイル名を連結できます。

$filename = $files_widgets->getPathname() . '/' . $files_widgets->getFilename();
$widget_text = file_get_contents($filename);

何か面白いことをしたい場合は、 SplFileObjectopenFileを取得するために使用することもできます。厄介なことに、SplFileObjectにはすべてのファイルの内容をすばやく取得する方法がないため、ループを作成する必要があります。

$fo = $files_widgets->openFile('r');
$widget_text = '';
foreach($fo as $line)
    $widget_text .= $line;
unset($fo);

コンテンツを1行ずつ取得するには、SplFileObjectをループする必要があるため、これはもう少し冗長です。これはオプションですが、を使用するだけの方が簡単ですfile_get_contents

于 2011-03-22T17:25:20.680 に答える