Created
October 22, 2013 13:16
-
-
Save vendethiel/ca0bf33fdd149bc1d6d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class XkcdParser | |
{ | |
/* @var array $last Data of the latest comic */ | |
private $last; | |
/* @var int $max Latest comic data ID */ | |
private $max; | |
public function __construct() | |
{ | |
$this->last = $this->query(); | |
$this->max = $this->last['num']; | |
} | |
/* | |
* returns a random xkcd comic, from 1 to last | |
* @see $this->last, $this->max | |
* @api | |
* | |
* @return array the comic data | |
*/ | |
public function random() | |
{ | |
$id = rand(1, $this->max); | |
return $this->query($id); | |
} | |
/* | |
* queries data for the specified comic | |
* @api | |
* | |
* @param int|string id Comic id or empty string for latest | |
*/ | |
public function query($id = '') | |
{ | |
if ($id == '' && $this->last) | |
return $last; | |
$url = $this->url($id); | |
return json_decode(file_get_contents($url), true); | |
} | |
/* | |
* displays a comic | |
* @param array $data the comic data ({@see query}) | |
* @return void | |
*/ | |
public function display($data) | |
{ | |
echo " | |
<img src='${data['img']}' /> | |
<p>${data['alt']}</p> | |
"; | |
} | |
/* | |
* Returns the JSON url for the specified comic | |
* | |
* @param int|strign $id Comic id or empty string for latest | |
* @return string Full URL | |
*/ | |
private function url($id = '') | |
{ | |
return 'http://xkcd.com/' . ($id ? "$id/" : '') . 'info.0.json'; | |
} | |
} | |
$xkcd = new XkcdParser(); | |
$xkcd->display($xkcd->random()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment