Last active
December 16, 2015 08:59
-
-
Save stamat/5409562 to your computer and use it in GitHub Desktop.
Get Goodreads.com books from the shelf and return JSON with no cover fallback
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 | |
function request($url) { | |
$c = curl_init(); | |
curl_setopt($c, CURLOPT_URL, $url); | |
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 3); | |
curl_setopt($c, CURLOPT_TIMEOUT, 5); | |
curl_setopt($c, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); | |
$response = curl_exec($c); | |
$responseInfo = curl_getinfo($c); | |
curl_close($c); | |
if (intval($responseInfo['http_code']) == 200) { | |
return $response; | |
} else { | |
return ''; | |
} | |
} | |
function getGoodreads($api, $user_id, $shelf, $per_page, $page, $sort) { | |
$gr = new SimpleXMLElement(request('http://www.goodreads.com/review/list/'.$user_id.'.xml?key='.$api.'&v=2&shelf='.$shelf.'&per_page='.$per_page.'&page='.$page.'&sort='.$sort)); | |
$resp = array(); | |
foreach ($gr->reviews->review as $item) { | |
$book = $item->book; | |
$parts = explode('/', $book->image_url); | |
$image = $book->image_url; | |
$id = count($parts)-2; | |
if($parts[$id] == 'nocover') //no cover fallback | |
$image = 'http://covers.openlibrary.org/b/isbn/'.$book->isbn.'-M.jpg'; | |
$str = '{ "title":"'.$book->title.'", "link":"'.$book->link.'", "image":"'.$image.'", "authors": ['; | |
$auts = array(); | |
foreach ($book->authors->author as $author) { | |
array_push($auts, '"'.$author->name.'"'); | |
} | |
$str = $str.implode(',',$auts).']}'; | |
array_push($resp, $str); | |
} | |
return '{"books":['.implode(',',$resp).']}'; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment