Skip to content

Instantly share code, notes, and snippets.

@stefanreimers
Created September 6, 2017 11:41
Show Gist options
  • Save stefanreimers/a754027cc299af921dee65064c829a6a to your computer and use it in GitHub Desktop.
Save stefanreimers/a754027cc299af921dee65064c829a6a to your computer and use it in GitHub Desktop.
PHP Script to turn RSS feeds into JSON objects - to be consumed by JavaScript
<?php
// Turn off all error reporting
error_reporting(0);
header('Content-Type: application/json');
$url = filter_input( INPUT_GET, 'feed', FILTER_VALIDATE_URL) ;
if($url == null || $url === false){
$json = array('error' => 'Invalid URL');
echo json_encode($json);
die();
}
$feed = new DOMDocument();
$feed->load( $url );
$json = array();
$main = $feed->getElementsByTagName('channel');
if($main == null) {
$main = $feed->getElementsByTagName('feed');
}
$json['source'] = $url;
$json['title'] = $main->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $main->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['language'] = $main->item(0)->getElementsByTagName('language')->item(0)->firstChild->nodeValue;
$json['copyright'] = html_entity_decode( $main->item(0)->getElementsByTagName('copyright')->item(0)->firstChild->nodeValue );
$items = $main->item(0)->getElementsByTagName('item');
$json['items'] = array();
$i = 0;
foreach($items as $item) {
try {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$link = $item->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$content = $item->getElementsByTagName('content')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
// Get related headlines
$description = str_replace('\\', '', $description);
preg_match_all('/href="([^"]+)"/', $description, $related);
$json['items'][$i] = array(
'title' => $title,
'description' => html_entity_decode(strip_tags($description)),
'pubDate' => strtotime($pubDate),
'link' => $link,
// 'content' => strip_tags($content),
'guid' => $guid
);
if($related[1] != null && !empty($related[1])) $json['items'][$i]['related'] = $related[1];
$i++;
} catch( Exception $e ) {
}
}
echo json_encode($json);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment