esedic
2/15/2017 - 4:28 PM

Custom K2 RSS with JSON data decode

Custom K2 RSS with JSON data decode

<?php
  // custom RSS feed for external service (note: NOT W3C compliant) with K2 json output: url?format=json
  header("Content-Type: application/rss+xml; charset=UTF-8");
  $rssfeed = '<?xml version="1.0" encoding="UTF-8"?>'. "\n";
  $rssfeed .= '<rss version="2.0" xmlns="http://backend.userland.com/rss2">'. "\n";
  $rssfeed .= '<channel>'. "\n";
        $rssfeed .= '<title>My domain</title>'. "\n";
        $rssfeed .= '<link>https://mydomain.com</link>'. "\n";
        $rssfeed .= '<description>My feed description.</description>'. "\n";
  $url = "https://mydomain.com/allnews?format=json";
  $content = file_get_contents($url);
  $json = json_decode($content, true);

  foreach (array_slice($json['items'],0,25) as $item) {
    // Use $field and $value here
  $rssfeed .= '<item>'. "\n";
  $rssfeed .= '<title><![CDATA[' . $item['title'] . ']]></title>'. "\n";
  $rssfeed .= '<link>https://mydomain.com' . $item['link'] . '</link>'. "\n";    // adding domain to get the full url
  $intro = html_entity_decode($item['introtext']);
  $intro = str_replace('&nbsp;', '', $intro);
  $intro = strip_tags($intro);
  $rssfeed .= '<description><![CDATA[' . $intro . ']]></description>'. "\n";
  $date = new DateTime($item['modified']);
  $date->modify('+2 hours');  //my K2 returns pubdate (modified)  in UTC format, so I had to add time zone difference in hours
  $rssfeed .= '<pubDate>' . $date->format("D, d M Y H:i:s +0200") . '</pubDate>'. "\n";
  $fulltext = html_entity_decode($item['fulltext']);
  $fulltext = str_replace('&nbsp;', ' ', $fulltext);
  $fulltext = strip_tags($fulltext);
  $rssfeed .= '<yandex:full-text><![CDATA[ ' . $fulltext . ']]></yandex:full-text>'. "\n";
  $rssfeed .= '</item>'. "\n";

  }

    $rssfeed .= '</channel>'. "\n";
    $rssfeed .= '</rss>';

  echo $rssfeed;
?>