Skip to content

Instantly share code, notes, and snippets.

@atbradley
Created September 22, 2016 12:37
Show Gist options
  • Save atbradley/f671d5d63b6cdb275e76b22ebb6f6e5e to your computer and use it in GitHub Desktop.
Save atbradley/f671d5d63b6cdb275e76b22ebb6f6e5e to your computer and use it in GitHub Desktop.
Retrieve book data from the LibraryThing Common Knowledge API.
<?php
namespace ocra\libraryThing;
/**
* Search LibraryThing's Common Knowledge API for a book and return and array with author/title and maybe year.
*/
function find_by_isbn($isbn) {
$lturl = 'http://www.librarything.com/services/rest/1.1/?method=librarything.ck.getwork&isbn=%s&apikey=%s';
$lturl = sprintf($lturl, $isbn, LIBRARYTHING_API_KEY);
$ckdata = file_get_contents($lturl);
//Librarything sometimes sends less-than-well-formed XML.
$ckdata = str_replace('&lt;![CDATA[', '<![CDATA[', $ckdata);
$ckdata = str_replace(']]&gt;', ']]>', $ckdata);
$ckdata = str_replace('&nbsp;', ' ', $ckdata);
$tidy = new \Tidy;
$tidyconf = array(
'input-xml' => true,
'output-xml' => true,
'escape-cdata' => true,
'add-xml-decl' => true,
'preserve-entities' => true,
'doctype' => 'omit',
'quote-nbsp' => true,
'hide-comments' => true,
'wrap' => 0,
);
$ckdata = $tidy->repairString($ckdata, $tidyconf, 'utf8');
$ckdata = $tidy->repairString($ckdata, $tidyconf, 'utf8');
$origerr = libxml_use_internal_errors(true);
$ckdata = new \SimpleXMLElement( $ckdata );
libxml_use_internal_errors($origerr);
if ( @$ckdata->ltml ) {
$ckdata->registerXPathNamespace('lt', 'http://www.librarything.com/');
$date = $ckdata->xpath('//lt:commonknowledge/lt:fieldList/lt:field[@name="originalpublicationdate"]//lt:fact');
if ( $date ) {
$year = @date('Y', strtotime((string)$date[0]));
}
$author = (string)$ckdata->ltml->item->author;
$title = (string)$ckdata->ltml->item->title;
$book = compact('author', 'title', 'year');
return $book;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment