How to convert json feed to rss in php?

Member

by deron , in category: PHP General , 9 months ago

How to convert json feed to rss in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 9 months ago

@deron 

To convert a JSON feed to RSS in PHP, you can follow these steps:

  1. Fetch the JSON feed using PHP's file_get_contents function or CURL.
  2. Parse the JSON feed using json_decode function to get an associative array.
  3. Create the RSS feed using XMLWriter class in PHP.
  4. Loop through the items in the JSON feed and add them to the RSS feed.
  5. Set the appropriate headers and output the RSS feed.


Here is an example code snippet to convert a JSON feed to RSS in PHP:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php

// Fetch the JSON feed
$json_feed = file_get_contents('http://example.com/json-feed');

// Decode the JSON feed
$data = json_decode($json_feed, true);

// Create the RSS feed
$xml = new XMLWriter();
$xml->openURI('php://output');
$xml->startDocument();
$xml->setIndent(true);
$xml->startElement('rss');
$xml->writeAttribute('version', '2.0');
$xml->startElement('channel');
$xml->writeElement('title', 'Converted RSS Feed');
$xml->writeElement('link', 'http://example.com');
$xml->writeElement('description', 'Converted RSS Feed from JSON');

// Loop through the items in the JSON feed and add them to the RSS feed
foreach ($data['items'] as $item) {
    $xml->startElement('item');
    $xml->writeElement('title', $item['title']);
    $xml->writeElement('link', $item['link']);
    $xml->writeElement('description', $item['description']);
    $xml->endElement();
}

$xml->endElement();
$xml->endElement();
$xml->endDocument();
$xml->flush();

?>


Make sure to replace the URL http://example.com/json-feed with the actual URL of the JSON feed you want to convert to RSS. This code will output the converted RSS feed to the browser. You can also save the output to a file by setting the filename in openURI method.