Page 1 of 1

PHP read files from directory

Posted: Wed Dec 23, 2009 4:03 am
by VitDavide
I am trying to do a simple blog in php and i am trying to read some text files from a directory named "articles". The idea is to loop through all text files and read and post their contents:

Code: Select all

            $Title="title";
            $content="12435 454 25 43 543";
        foreach (string file in directory)
        {
            //read from file
            //assign file name to title
            //assign file content to $content
        }
        //post everything on page
            echo('<h2>$Title</h2>');
            echo('$content');
            echo('<hr>');
 
I am totally new to PHP even though i know some other programming languages like Java, C# and C++.

Thank you!

Re: PHP read files from directory

Posted: Wed Dec 23, 2009 4:26 am
by AntonioCS
Use scandir to get a list of the files in the directory and then in the loop use file_get_contents to get the text inside the files.

Re: PHP read files from directory

Posted: Wed Dec 23, 2009 12:49 pm
by AbraCadaver
I would use glob().

Code: Select all

foreach (glob("/path/to/articles/*.txt") as $file) {
    $content = file_get_contents($file);
    echo "<h2>$file</h2>";
    echo nl2br($content);
    echo "<hr>";
}

Re: PHP read files from directory

Posted: Thu Dec 24, 2009 8:40 am
by VitDavide
AbraCadaver wrote:I would use glob().

Code: Select all

foreach (glob("/path/to/articles/*.txt") as $file) {
    $content = file_get_contents($file);
    echo "<h2>$file</h2>";
    echo nl2br($content);
    echo "<hr>";
}
Thank you very much! That worked :)!

Re: PHP read files from directory

Posted: Thu Dec 24, 2009 9:24 am
by omniuni
glob() does simple wildcards!? WOW!!!

Ya learn something new every day. I have some code I can definitely simplify with this!

Oh, and you may need to add a stripslashes() and/or htmlentities() on file_get_contents()...