I am very inexperienced with PHP. I have a folder on a website which will receive files named with a numeric date structure. I need href links to be created for the files which are dropped into this folder. I need the link text to be formatted by with a textual month and numeric day. For example:
File name "01-02-22 BULLETIN.pdf" becomes
<href="bulletins/2022/$file">January 2</a>.
I have been messing with the code below from this post PHP to create Links for files in a folder, but I can't seem to figure it out. The links are appearing but any date formatting I attempt returns "error Call to a member function format()."
Thanks for your help!
<?php
$dir = "bulletins/2022/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "<a href=bulletins/2022/$file>$file</a><br>";
}
closedir($dh);
}
}
?>
My Answer:
: 20210101_file.pdf
Desired link text: January 1
Here is a PHP script that will scan the folder for files and create href links with the formatted date text:
php
$folder = 'path/to/folder'; // Specify the path to the folder here
$files = scandir($folder);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$date = substr($file, 0, 8); // Extract the date from the file name
$timestamp = strtotime($date); // Convert the date to a timestamp
$formatted_date = date('F j', $timestamp); // Format the date as 'Month Day'
echo '' . $formatted_date . '
';
}
}
?>
Replace `'path/to/folder'` with the actual path to your folder. This script will loop through all the files in the folder, extract the date from the file name, convert it to a timestamp, format it as 'Month Day', and create an href link with the formatted date text.
Rate this post
3 of 5 based on 3371 votesComments