Stack2XML Source Code
Nathan Osman — 2¬†years, 6¬†months ago


<?php
/* Outputs the specified XML. */
function OutputXML($contents)
{
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" . $contents;
}
/* Displays an error when something goes wrong. */
function FatalError($error)
{
OutputXML("<error>\n <description>$error</description>\n</error>");
}
/* Retrieves JSON data from a remote URL. */
function FetchData($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
/* There was an error if $data is FALSE. */
if($data === FALSE)
FatalError('There was an error retrieving the data from the API servers.');
curl_close($ch);
return json_decode($data);
}
/* Lookup the version and method requested. */
$version = $_GET['version'];
$method = $_GET['method'];
/* Combine all of the other query string parameters. */
$params = array();
foreach($_GET as $key => $value)
{
if($key != 'version' && $key != 'method')
$params[] = "$key=$value";
}
/* Fetch the data from the specified URL. */
$data = FetchData("http://api.stackexchange.com/$version/$method?" . implode($params, '&'));
/* Safely encodes output for XML. */
function xmlentities($xml)
{
return str_replace(array('&', '<', '>'),
array('&amp;', '&lt;', '&gt;'),
html_entity_decode($xml));
}
/* Recursive function that renders the XML from the JSON dictionary. */
function RenderTag($object, $ws_level, $name='')
{
$output = '';
if(is_object($object))
{
$members = get_object_vars($object);
foreach($members as $key => $value)
{
if(is_object($value) || is_array($value))
$output .= str_repeat(' ', $ws_level) . "<$key>\n" .
RenderTag($value,$ws_level + 2, $key) .
str_repeat(' ', $ws_level) . "</$key>\n";
else
$output .= str_repeat(' ', $ws_level) . "<$key>" . xmlentities($value) . "</$key>\n";
}
}
elseif(is_array($object))
{
$mod_name = substr($name, 0, strlen($name) - 1);
foreach($object as $value)
$output .= str_repeat(' ', $ws_level) . "<$mod_name>\n" .
RenderTag($value,$ws_level + 2, $key) .
str_repeat(' ', $ws_level) . "</$mod_name>\n";
}
else
$output .= str_repeat(' ', $ws_level) . "$object\n";
return $output;
}
/* Return the XML document to the client. */
OutputXML("<response>\n" . RenderTag($data, 2) . "</response>");
?>