Skip to content

Instantly share code, notes, and snippets.

@sven337
Forked from evert/disqus-to-json.php
Created February 5, 2020 20:16
Show Gist options
  • Save sven337/456197982ed75531a4fad4ec95092eac to your computer and use it in GitHub Desktop.
Save sven337/456197982ed75531a4fad4ec95092eac to your computer and use it in GitHub Desktop.
Convert Disqus export to a JSON file
<?php
$xml = simplexml_load_file('php://stdin');
$threads = [];
$posts = [];
$userMap = [
'evertp' => [
'url' => 'https://evertpot.com',
'avatar' => 'https://s.gravatar.com/avatar/9e9b4f80c65dc6076d74cd421084e4fc?s=200',
]
];
foreach($xml->thread as $thread) {
$thread = [
'id' => (string)$thread->attributes('http://disqus.com/disqus-internals')['id'],
'url' => (string)$thread->link,
'post_id' => (string)$thread->id,
'comments' => [],
];
$threads[$thread['id']] = $thread;
}
foreach($xml->post as $post) {
$threadId = (string)$post->thread->attributes('http://disqus.com/disqus-internals')['id'];
$postId = (string)$post->attributes('http://disqus.com/disqus-internals')['id'];
if ($post->parent) {
$parentId = (string)$post->parent->attributes('http://disqus.com/disqus-internals')['id'];
} else {
$parentId = null;
}
$posts[$postId] = [
'id' => $postId,
'created' => (string)$post->createdAt,
'isDeleted' => (string)$post->isDeleted !== 'false',
'isClosed' => (string)$post->isClosed !== 'false',
'isSpam' => (string)$post->isSpam !== 'false',
'name' => (string)$post->author->name,
'user' => (string)$post->author->username,
'message' => (string)$post->message,
'children' => [],
];
if ($parentId) {
$posts[$parentId]['children'][] =& $posts[$postId];
} else {
$threads[$threadId]['comments'][] =& $posts[$postId];
}
}
function convertComments(array $comments) {
global $userMap;
$result = [];
foreach($comments as $comment) {
if($comment['isDeleted']) {
continue;
}
if($comment['isSpam']) {
continue;
}
$newComment = [
'created' => $comment['created'],
'name' => $comment['name'],
'disqusUser' => $comment['user'],
'message' => $comment['message'],
'children' => convertComments($comment['children']),
];
if (isset($userMap[$newComment['disqusUser']])) {
$newComment['url'] = 'https://evertpot.com/';
$newComment['avatar'] = 'https://s.gravatar.com/avatar/9e9b4f80c65dc6076d74cd421084e4fc?s=200';
}
$result[] = $newComment;
}
return $result;
}
function convertThreads(array $threads) {
$result = [];
foreach($threads as $thread) {
if (!$thread['comments']) {
continue;
}
$result[$thread['post_id']] = convertComments($thread['comments']);
}
return $result;
}
$threads = convertThreads($threads);
echo json_encode($threads, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment