Helpful Information
 
 
Category: Post a PHP snippet
Word of the Day

Here's a little snippet to get the Word of the Day from Dictionary.com.



function wotd() {
$xml = simplexml_load_string(file_get_contents('http://dictionary.reference.com/wordoftheday/wotd.rss'));
$wotd = $xml->channel->item->description;
$link = $xml->channel->item->link;
$wotd = explode(':', $wotd);
return array('wotd'=>$wotd[0], 'def'=>$wotd[1], 'link'=>$link);
}


It's a basic script, and if you have high traffic you might want to use something along this line...



function get() {
$xml = cacheCheck();
if($xml === false) {
return false;
}
$xml = simplexml_load_string($xml);
$wotd = $xml->channel->item->description;
$link = $xml->channel->item->link;
$wotd = explode(':', $wotd);
return array('wotd'=>$wotd[0], 'def'=>$wotd[1], 'link'=>$link);
}

function cacheCheck($dir='cache/', $expire=3600) {
$good = true;
$filename = $dir.'wotd';
if (file_exists($filename)) {
$time = filectime($filename);
if($time > (time() - $expire)) {
$good = false;
}
$xml = file_get_contents($filename);
}

if ($good) {
$xml = file_get_contents('http://dictionary.reference.com/wordoftheday/wotd.rss');
if (!$xml) {
return false;
}else{
file_put_contents($filename, $xml);
}
return $xml;
}
}


The cache is untested, but it should work.

You could set the expire time to 1 day as "the word of the day" will most probably change only once a day :D

I suppose so. But that'd be more difficult. Because if your first hit of the day is at, say 9 in the morning, but the next day you get the first hit at 8 in the morning. Same word, different day.

But I do see your point.

Well I thought about that. You could meke the cache valid untill some time. You save the timestamp of when the last time was and check if it's still valid. You could set that the cache is valid untill 0:00 of the next day and if someone opens the page after that you cache it and set the expiure date to 0:00 of the next day. You'd be forcing an update on midnight.

Good point.

I did some editing, and a simple date check would be easy enough. I also changed the $xml check.



function cacheCheck($dir='cache/') {
$get = true;
$filename = $dir.date('Ymd');
if (file_exists($filename)) {
$get = false;
$xml = file_get_contents($filename);
}
if ($get) {
$xml = file_get_contents('http://dictionary.reference.com/wordoftheday/wotd.rss');
if (!$xml) {
return false;
}else{
file_put_contents($filename, $xml);
}
}
return $xml;
}


This way you get a cache and a directory of WOTD files. Alternatively, you could store it in a database and do all the checks in there.

Just wanted to add my two cents in saying that this uses a function which is only available in PHP5 (file_put_contents()). Also, in PHP4, simplexml is by default disabled as opposed to PHP5 where it is enabled by default.










privacy (GDPR)