Hi there,

I am somewhat new to PHP but catching on fairly well. However, I'm currently stumped.

I would like to access the newest XML file in a folder. Right now my code is hardwired so everytime I want to see the newest file I have to actually enter it into the PHP code. I know there is a way to get it to read the newest file, but I can't figure it out for the life of me.

The code I'm using is (I've bolded the part I need to apply the query to):

<?php

// set name of XML file
$file = "xml_files/article_01.xml";

// load file
$xml = simplexml_load_file($file) or die ("Unable to load XML file!");

// access XML data

echo nl2br(" " . $xml->headline . "\n");
echo nl2br(" " . $xml->byline . "\n");
echo nl2br(" " . $xml->author . "\n\n");
echo nl2br(" " . $xml->article . "\n");

?>

Recommended Answers

All 3 Replies

Hi.

You can use the filectime function to determine when a file was last changed and the glob function to get a list of files in a directory.

Using that, you can determine which of the files was last edited and display that.

For example:

<?php
header("Content-Type: text/plain");
$files = glob("*");

$latestFile = null;
$latestTime = 1;
foreach($files as $_file)
{
	$currentTime = filectime($_file);
	if($currentTime > $latestTime) {
		$latestTime = $currentTime;
		$latestFile = $_file;
	}
}

echo "The file that was changed last: ", PHP_EOL;
echo " ", $latestFile;
?>

Please excuse my newness, but how would that work in context to the code I posted? What you wrote makes sense but I'm not sure how to make it work with my code...? Thanks in advance!

My code would essentially replace your $file = "xml_files/article_01.xml"; line. But make sure you change the $file in your simplexml_load_file($file) to simplexml_load_file($latestFile) .

And also, you would want to remove the echo and header lines from the code I posted.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.