I am trying to set up a php script that will look through an XML, and if an item has a pubDate of more than 7 days old, it deletes the entire item. What I have come up with so far is:
<?php
$rss = new DOMDocument();
$url = 'http://www.url.net/app/Test.xml';
$rss->load($url);
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('date')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 50;
for($x=0;$x<$limit;$x++) {
date_default_timezone_set('America/Los_Angeles');
$newDate = date("D, d M Y G:i:s -0400", strtotime("-8 day"));
$date = date('D, d M Y G:i:s -0400', strtotime($feed[$x]['date']));
$theitem = date('D, d M Y G:i:s -0400', strtotime($feed[$x]['date']));
if ($date > $newDate) {
echo "Don't delete";
}
else {
echo "Delete";
}
}
?>
This gives me 50 echoes, only 1 of which is Delete, while the XML actually only houses 10 items, and only one of them should remain. Can you give me some guidance for getting this set up right, and then also on how to remove the item, once I have identified them properly?
You're comparing the values as strings in the RSS date format. This is something like Mon, 15 Aug 2005 15:52:01 +0000
and for example Fri
will be smaller then Mon
. I suggest you compare the result of strtotime()
directly.
$newDate = strtotime("-8 day");
$date = strtotime($feed[$x]['date']);
if ($date > $newDate) {
echo "Don't delete";
} else {
echo "Delete";
}
Another way is using Xpath with a callback into PHP: https://stackoverflow.com/a/23683347/2265374