PHP — RSS to JSON

Bayu Nugroho
Dec 23, 2020

--

<?php
header(‘Content-Type: application/json’);
$feed = new DOMDocument();

$url = “https://example.bayunugroho404.xml”;
$feed->load($url);
$json = array();

$json[‘title’] = $feed->getElementsByTagName(‘channel’)->item(0)->getElementsByTagName(‘title’)->item(0)->firstChild->nodeValue;
$json[‘description’] = $feed->getElementsByTagName(‘channel’)->item(0)->getElementsByTagName(‘description’)->item(0)->firstChild->nodeValue;
// $json[‘link’] = $feed->getElementsByTagName(‘channel’)->item(0)->getElementsByTagName(‘link’)->item(0)->firstChild->nodeValue;

$items = $feed->getElementsByTagName(‘channel’)->item(0)->getElementsByTagName(‘item’);

$json[‘item’] = array();
$i = 0;

foreach($items as $item) {

$title = $item->getElementsByTagName(‘title’)->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName(‘description’)->item(0)->firstChild->nodeValue;
$date = $item->getElementsByTagName(‘pubDate’)->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName(‘guid’)->item(0)->firstChild->nodeValue;
$thumbnail = $item->getElementsByTagName(‘thumbnail’)->item(0)->firstChild->nodeValue;

$json[‘item’][] = array(“title”=>$title,”description”=>$description,”image”=>$thumbnail,”date”=>$date);

}

echo json_encode($json);

?>

change name variable url to your xml format

--

--

Bayu Nugroho
Bayu Nugroho

Written by Bayu Nugroho

Passionate programmer obsessed with perfection. Enjoys creating web and mobile applications, exploring music, technical blogging, and more.

No responses yet