Adventures in C, Linux, and open source
February 20, 2020
I'm new to PHP, so this is pretty exciting to me.
I needed a way to dynamically list blog pages for my blog index, but I want to avoid using javascript where possible. The solution was to find all files in the blog directory tree, sort them by creation time, and extract the page title. This can all be done in PHP.
$files = glob("*/*/*.html");
array_multisort(array_map('filectime', $files), SORT_NUMERIC, SORT_DESC, $files);
for($i=0;$i<count($files);$i++) {
$f = file_get_contents($files[$i]);
if(!$f) continue;
if(!preg_match("/<h1 class=\"post_title\">(.*)<\/h1>/siU", $f, $match)) continue;
echo "<tr><td>" . date('Y-m-d', filectime($files[$i])) . "</td><td><a href=\"" . $files[$i] . "\">" . trim($match[1]) . "</a></td></tr>";
}
All html files in the blog directory tree are fetched using glob()
and sorted by change/creation time using array_multisort()
and filectime()
. The contents of each file are searched for a specific tag (<h1 class="post_title">)
, which is used as the title to display in the blog index. A table row is then printed using the file change/creation time and the post title.
Since GitHub Pages only supports static pages, the PHP page is just used to generate the corresponding HTML page.
Explorer of cool technologies, amateur programmer and linux admin, and generally curious about anything related to computers and open source software.
More about me →