Skip to content

Instantly share code, notes, and snippets.

@rogeriolino rogeriolino/rsstojson.php
Last active May 25, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.