Getting a random Wikipedia article using PHP + cURL
The following code gets a completely random page from Wikipedia and returns some HTML code with a link to the article. Visiting http://en.wikipedia.org/wiki/Special:Random in your browser will automatically redirect to a random article and the code takes in to account the redirect and gives you the information on the last page in the redirect.
<?php
function get_random_wikipedia_article() {
  if (!function_exists('curl_init')) return FALSE;
  $url = 'http://en.wikipedia.org/wiki/Special:Random';
  $options = array(
    CURLOPT_RETURNTRANSFER => true,     // return web page
    CURLOPT_HEADER         => false,    // don't return headers
    CURLOPT_FOLLOWLOCATION => true,     // follow redirects
    CURLOPT_ENCODING       => "",       // handle all encodings
    CURLOPT_USERAGENT      => "spider", // who am i
    CURLOPT_AUTOREFERER    => true,     // set referer on redirect
    CURLOPT_CONNECTTIMEOUT => 30,      // timeout on connect
    CURLOPT_TIMEOUT        => 30,      // timeout on response
    CURLOPT_MAXREDIRS      => 3,       // stop after 10 redirects
  );
  
$ch = curl_init($url);
  curl_setopt_array($ch, $options);
  $content = curl_exec($ch);
  $err = curl_errno($ch);
  $errmsg = curl_error($ch);
  $header = curl_getinfo($ch);
  curl_close($ch);
  if (
preg_match('/<title>(.*?)<\/title>/i', $content, $matches)) {
    $title = str_replace(' - Wikipedia, the free encyclopedia', '', $matches[1]);
  }
  return 
'<a href="'. $header['url'] .'">'. $title .'</a>';
}
?>

Comments
viktor
Fri, 2012-07-06 16:20
Permalink
Great!!
works perfectly!! thank you!!! :)
Karthik
Mon, 2013-01-14 05:19
Permalink
Perfect, Thanks :), How can
Perfect, Thanks :), How can we write in wikipedia via curl ?