Jump to content

[SOLVED] Insert content from files in a directory


conrad

Recommended Posts

I'm not sure how to ask this question or search for the answer so here goes:

 

At the moment I have several of these:

<?php include_once("models/xxx.html"); ?>

<?php include_once("models/yyy.html"); ?>

<?php include_once("models/zzz"); ?>

 

How do I have PHP display the contents (rather than file name) of several HTML files in a directory without calling each file individually?

 

Thank you for your help!

$dir = "/the/directory/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
      if(!is_dir($file)) include_once($dir.$file);
        }
        closedir($dh);
    }
}

 

Haven't tested taht fully, but should work

Thank you veru much for your help! Knowing next to nothing about PHP I wasn't sure just how to use the "foreach()" loop. When I saw the code written out to copy and paste I took the bait. Thank you for posting!

 

The code seems to work fine although I have a question:

 

When I inserted

 

<?php

$dir = "models/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
      if(!is_dir($file)) include_once($dir.$file);
        }
        closedir($dh);
    }
}

?>

 

Before my previously mentioned

 

<?php include_once("models/xxx.html"); ?>

<?php include_once("models/yyy.html"); ?>

<?php include_once("models/zzz.html"); ?>

 

All of the individual calls to "include_once" disappeared. I am left with my list of files from the "models" directory above my 'header' (as expected) with nothing below the 'header' where I have written the "include_once"s (plural). I'm not complaining but curious about why.

 

Thanks again for the quick help!

If I understand your question correctly, putting that loop at the top of your page will as you said include the files above your header....

 

If you still have the other includes' in place they will not include the file for one reason....

 

include_once

 

It will only include a file once! If you want to include a single file more thatn once just use include :)

readdir accesses the files in the order they are in the directory tree, which is generally the order in which they were created. To get an alphabetical list would require reading the files into an array and sorting it or using the glob() function, which by default does an alphabetical sort. For any other arbitrary order, you would need to make a specific list and include_once() the files in order using that list.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.