Skip to content

Instantly share code, notes, and snippets.

@black23
Forked from atbradley/librarything.php
Created June 13, 2018 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save black23/fc0e12cbf02059b740201b2f7bd05bb4 to your computer and use it in GitHub Desktop.
Save black23/fc0e12cbf02059b740201b2f7bd05bb4 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