Skip to content

Instantly share code, notes, and snippets.

@crankycoder
Forked from coryalder/blogpost.md
Created January 22, 2014 17:23
Show Gist options
  • Save crankycoder/8562998 to your computer and use it in GitHub Desktop.
Save crankycoder/8562998 to your computer and use it in GitHub Desktop.
<?php
// code to accompany this blog post http://objectivesea.tumblr.com/post/9033067018/safaribooks
// body of blog post is included in a separate file from this gist.
try
{
//create or open the database
$database = new SQLite3('/Users/cory/Desktop/Safari.sqlite');
if ($database) echo "Database connection open...\n";
$booksQuery = 'SELECT * from ZBOOK where ZOFFLINESTATUS = "offline"';
if($result = $database->query($booksQuery)) {
echo "Found " . $result->numColumns() . " books stored offline\n";
while($row = $result->fetchArray()) {
echo "Saving book " . $row['ZTITLE'] . "\n";
save_a_book($row['ZTITLE'], $row['Z_PK'], $database, $row['ZFPID']);
}
} else echo "Database failed to return results for query: " . $booksQuery;
}
catch(Exception $e)
{
die($error);
}
function save_a_book($name, $book_id, $database, $fpid) {
$query = 'SELECT ZHTMLBODY, Z_PK, ZORDERINDEX from ZPAGE where ZBOOK = "' . $book_id . '" ORDER BY ZORDERINDEX';
if($result = $database->query($query)) {
// make dir
mkdir_recursive(sanitize($name, TRUE));
$counter = 1;
while($row = $result->fetchArray()) {
$myFile = "./" . sanitize($name, TRUE) . "/pg_" . $counter . ".html";
$fh = fopen($myFile, 'w') or die("can't open file ". $row['Z_PK']);
$stringData = $row['ZHTMLBODY'];
fwrite($fh, $stringData);
fclose($fh);
$counter++;
print("Wrote page #: {$row['Z_PK']} to file {$myFile}\n");// . "Director: {$row['Director']} <br />" . "Year: {$row['Year']} <br /><br />");
}
mkdir_recursive(sanitize($name, TRUE) . "/images/" . $fpid);
}
}
function mkdir_recursive($pathname)
{
is_dir(dirname($pathname)) || mkdir_recursive(dirname($pathname));
return is_dir($pathname) || @mkdir($pathname);
}
function sanitize($string = '', $is_filename = FALSE)
{
// Replace all weird characters with dashes
$string = preg_replace('/[^\w\-'. ($is_filename ? '~_\.' : ''). ']+/u', '-', $string);
// Only allow one dash separator at a time (and make string lowercase)
return mb_strtolower(preg_replace('/--+/u', '-', $string), 'UTF-8');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment