PHP read files from directory

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
VitDavide
Forum Newbie
Posts: 3
Joined: Wed Dec 23, 2009 3:58 am

PHP read files from directory

Post 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!
AntonioCS
Forum Newbie
Posts: 11
Joined: Tue Jan 15, 2008 12:31 pm

Re: PHP read files from directory

Post 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.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: PHP read files from directory

Post 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>";
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
VitDavide
Forum Newbie
Posts: 3
Joined: Wed Dec 23, 2009 3:58 am

Re: PHP read files from directory

Post 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 :)!
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: PHP read files from directory

Post 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()...
Post Reply