Skip to content

Instantly share code, notes, and snippets.

@rogeriolino
Last active May 25, 2018 20:40
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 rogeriolino/5d3b70a12e855a5b484aa0f74af91e00 to your computer and use it in GitHub Desktop.
Save rogeriolino/5d3b70a12e855a5b484aa0f74af91e00 to your computer and use it in GitHub Desktop.
RSS to JSON
<?php
$url = isset($_GET['url']) ? $_GET['url'] : '';
if (filter_var($url, FILTER_VALIDATE_URL) === false || strtolower(substr($url, 0, 4)) !== 'http') {
echo("URL inválida: $url");
exit();
}
$proxy = null; // "http://192.168.0.10:3128"
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
preg_match("/charset=([\w-]*)/", $headers, $output_array);
$chartset = isset($output_array[1]) ? $output_array[1] : 'UTF-8';
if ($chartset !== 'UTF-8') {
$body = mb_convert_encoding($body, 'UTF-8', $chartset);
}
$body = preg_replace("/<\?xml.+\?>/", "", $body);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
$feed = new DOMDocument();
$feed->loadXML($body);
$channel = $feed->getElementsByTagName('channel')->item(0);
$title = $channel->getElementsByTagName('title')->item(0)->textContent;
$description = $channel->getElementsByTagName('description')->item(0)->textContent;
$link = $channel->getElementsByTagName('link')->item(0)->textContent;
$json = [
'title' => trim($title),
'description' => trim($description),
'link' => trim($link),
'items' => [],
];
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
foreach($items as $item) {
$title = $item->getElementsByTagName('title')->item(0)->textContent;
$description = $item->getElementsByTagName('description')->item(0)->nodeValue;
$json['items'][] = [
'title' => trim($title),
'content' => trim($description),
];
}
echo json_encode($json);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment