PHP word of the day

Let us talk about scripts, HTML, Perl, PHP, apache, etc.
User avatar
Stevyn
SysOp
Posts:1786
Joined:Mon Nov 09, 2009 10:03 am
Location:Japan
Contact:
PHP word of the day

Post by Stevyn » Sun Nov 29, 2009 8:34 am

from http://codingforums.com/showthread.php?t=74307

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

PHP Code:

Code: Select all

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...

Code: Select all

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 updated edit:

Code: Select all

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;         
    }  

Post Reply