too long

I have a php script that will echo a list of files from a folder and display them randomly on my page.

At the moment it displays the url of the file for example: what-can-cause-tooth-decay.php

i would like it to display the page title <title>What can cause tooth decay</title>.

Current code:

<?php 

if ($handle = opendir('health')) {
    $fileTab = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $fileTab[] = $file; 
        }
    }
    closedir($handle);
    shuffle($fileTab);
    foreach($fileTab as $file) {
        $thelist .= '<p><a href="../health/'.$file.'">'.$file.'</a></p>';
    }
}
?>
<?=$thelist?>

Many thanks

I see a couple of possible approaches:

  • You could parse the files. Should be possible by running a regex over the results of file_get_contents.
  • Place some text file somewhere, which maps file names to titles. Load it into memory and use it to populate an array which you can use to map the file names. Let it have file_name.html Title on each line, or something like that.
  • Use a naming convention, so the titles can be inferred from the filenames. Something like "capizalize first letter, turn '_' into space"

Downsides of the 2nd and 3rd approach: You'd have to keep it consistent with the actual title-elements in the files. Problem with the first approach: You have to read every file into memory - could be a performance problem with many/big files. To solve this, I could imagine writing a script which looks through all the files and generates the lookup text file. Whenever you change a title in a file, or add/remove files, you'd just need to rerun that script.