Skip to content

Instantly share code, notes, and snippets.

@jandk
Created January 31, 2012 10:02
Show Gist options
  • Select an option

  • Save jandk/1709716 to your computer and use it in GitHub Desktop.

Select an option

Save jandk/1709716 to your computer and use it in GitHub Desktop.
Create an SQL from XKCD JSON feed
<?php
header('Content-type: text/plain; charset=utf-8');
$sql = <<<SQL
DROP TABLE IF EXISTS `xkcd`;
CREATE TABLE `xkcd` (
`id` int(11) NOT NULL DEFAULT '0',
`date` date DEFAULT NULL,
`image` text CHARACTER SET utf8,
`title` text CHARACTER SET utf8,
`safe_title` text CHARACTER SET utf8,
`alt` text CHARACTER SET utf8,
`link` text CHARACTER SET utf8,
`news` text CHARACTER SET utf8,
`transcript` text CHARACTER SET utf8
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
SQL;
echo $sql . "\n\n";
function sql_replace($str)
{
if (is_null($str))
return 'NULL';
if (is_numeric($str))
return $str;
$str = str_replace(
array("\0", "\n", "\r", "\\", "'", "\""),
array('\0', '\n', '\r', '\\\\', '\\\'', '\"'),
$str
);
return "'$str'";
}
$json = json_decode(file_get_contents('http://xkcd.com/info.0.json'));
$num = (int) $json->num;
$comics = array();
for ($i = 1; $i <= $num; $i++)
{
if ($i == 404)
continue;
$json = file_get_contents('http://xkcd.com/' . $i . '/info.0.json');
$json = json_decode($json, true);
$values = array(
$json['num'],
$json['year'] . '-' . $json['month'] . '-' . $json['day'],
$json['img'],
$json['title'],
$json['safe_title'],
$json['alt'],
$json['link'],
$json['news'],
$json['transcript']
);
$values = array_map('sql_replace', $values);
$values = implode(', ', $values);
printf("INSERT INTO xkcd VALUES( %s );\n", $values);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment