A few weeks ago, Jamie Bicknell notified me he read my article about the Random PHP function. Because I didn’t publish any code, he wrote a 3 line implementation of how he would fetch the functions for the randomness.
I promised him I would publish the code that weekend, and here we are, a few weeks later…
The script actually parses the http://php.net/quickref.php page, saves the result, and redirects the user.
$cacheFile = './functions.tmp';
if (!is_file($cacheFile)) {
$quickref = 'http://php.net/quickref.php';
$xml = DOMDocument::loadHTMLFile($quickref);
$links = $xml->getElementsByTagName('a');
$functions = array();
foreach ($links as $link) {
if (substr($link->getAttribute('href'), 0, 8) == '/manual/') {
$functions[$link->nodeValue] = $link->getAttribute('href');
}
}
file_put_contents($cacheFile, serialize($functions));
} else {
$functions = unserialize(file_get_contents($cacheFile));
}
$function = $functions[array_rand($functions)];
$function = 'http://php.net' . $function;
header('Location: ' . $function, true, 303);
die();
Some improvements:
- Invalidate the cache file when a new PHP version is announced.
- Read random lines from the file (instead of loading the complete array in the memory).
Update: Forgot the mention the actual blogpost of Jamie Bicknell…