Skip to content

Instantly share code, notes, and snippets.

@Athari
Created May 15, 2015 10:23
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 Athari/8ef3b657272480d166c8 to your computer and use it in GitHub Desktop.
Save Athari/8ef3b657272480d166c8 to your computer and use it in GitHub Desktop.
Stack Exchange Answers Atom Feed
<?php
function oops ($message = '')
{
http_response_code(400);
die($message);
}
function get_json ($url)
{
$json = json_decode(gzdecode(file_get_contents($url)), true);
if (isset($json['backoff']))
oops('Backoff!');
return $json['items'];
}
function format_date ($date)
{
return gmdate('Y-m-d\TH:i:s\Z', $date);
}
$site = $_GET['site'];
if (preg_match('#^[a-z\.]+$#', $site) == 0)
oops('Wrong site!');
$mode = $_GET['mode'];
if ($mode != 'answers')
oops('Wrong mode!');
header('Content-type: text/html; charset=utf-8');
$seinfo = get_json("https://api.stackexchange.com/2.2/info?site={$site}&filter=!7nFLaVmuZ..LGXU.WToUuFgUGa0j9Phai8")[0]['site'];
$seanswers = get_json("https://api.stackexchange.com/2.2/answers?order=desc&sort=creation&site={$site}&filter=!*c8AgooR)8mGi4bMMz*-hGVrFJcmOwIQNoF5e");
$feed = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom"/>');
$feed->addChild('title', $seinfo['name'] . ' Answers');
$feed->addChild('subtitle', 'For ' . $seinfo['audience']);
$feed->addChild('icon', $seinfo['icon_url']);
$feed->addChild('logo', $seinfo['logo_url']);
$feed->addChild('id', $seinfo['site_url'] . '/feeds');
$feed->addChild('updated', format_date($seanswers[0]['creation_date']));
$link = $feed->addChild('link');
$link->addAttribute('href', $seinfo['site_url']);
$author = $feed->addChild('author');
$author->addChild('name', $seinfo['name'] . ' Atom');
foreach ($seanswers as $seanswer) {
$entry = $feed->addChild('entry');
$entry->addChild('title', $seanswer['title']);
$link = $entry->addChild('link');
$link->addAttribute('href', $seanswer['link']);
$entry->addChild('id', $seanswer['link']);
$entry->addChild('updated', format_date($seanswer['creation_date']));
$content = $entry->addChild('content', $seanswer['body']);
$content->addAttribute('type', 'html');
$author = $entry->addChild('author');
$author->addChild('name', $seanswer['owner']['display_name']);
$author->addChild('uri', $seanswer['owner']['link']);
}
header('Content-type: application/atom+xml');
echo($feed->asXML());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment