Skip to content

Instantly share code, notes, and snippets.

@oodavid
Last active December 15, 2015 23:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oodavid/5344381 to your computer and use it in GitHub Desktop.
Save oodavid/5344381 to your computer and use it in GitHub Desktop.
PHP script to convert tumblr blog articles to jekyll posts, modify the settings then simply run this in your terminal: php tumblr2jekyll.php More on the blog - http://oodavid.com/2013/04/09/convert-from-tumblr-to-jekyll-using-php.html
<?php
//
// Settings
//
// Blog URL
$blog = 'oodavid.tumblr.com';
// Tumblr API key - register for one here: http://www.tumblr.com/oauth/apps
$api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
// Local folder to write to - PHP must be able to write here
$folder = '/home/david/Desktop/jekyllposts/';
//
// Settings encoding
//
$blog = urlencode($blog);
$api_key = urlencode($api_key);
//
// Read the number of posts
//
$url = "http://api.tumblr.com/v2/blog/{$blog}/info?api_key={$api_key}";
$ch = curl_init($url);
curl_setopt_array( $ch, array( CURLOPT_RETURNTRANSFER => true ) );
$result = json_decode(curl_exec($ch), true);
$posts = $result['response']['blog']['posts'];
//
// Download and process the posts in batches of 20 - it's an API limit
//
for ($n=0; $n<$posts; $n+=20){
// Read the posts
$url = "http://api.tumblr.com/v2/blog/{$blog}/posts?api_key={$api_key}&limit=20&offset={$n}";
$ch = curl_init($url);
curl_setopt_array( $ch, array( CURLOPT_RETURNTRANSFER => true ) );
$result = json_decode(curl_exec($ch), true);
// Loop the posts
foreach($result['response']['posts'] AS $post){
if(isset($post['title']) && isset($post['body'])){
// File-Name
$date = date('Y-m-d', $post['timestamp']);
$filename = "{$date}-{$post['slug']}.html";
// Title
$title = '"' . str_replace('"', '\"', $post['title']) . '"';
// Tags
$tags = $post['tags'] ? "\ntags: \n- " . implode("\n- ", $post['tags']) : '';
// File-Contents
$contents = <<<HEREHTML
---
layout: blog
title: {$title}{$tags}
---
{$post['body']}
HEREHTML;
// Write to file
$fh = fopen("{$folder}{$filename}", 'c+');
fwrite($fh, $contents);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment