2 August 2017

Instagram gives out json feed. You can use this little php snippet to create rss feed from the given json. The script leverages paging, which enables you to control the items count in the output feed.

Source code viewer
  1. <?php
  2. // Content type in header to xml.
  3. header('Content-type: text/xml');
  4.  
  5. // Your instagram user, how many pages to pull from instagram.
  6. $instagramUser = 'USER';
  7. $limit = 3;
  8.  
  9. // Define variables.
  10. $instagramJsonUrl = 'https://www.instagram.com/' . $instagramUser . '/?__a=1';
  11. $has_next_page = 1;
  12. $end_cursor = null;
  13. $count = 1;
  14. $instagram = null;
  15.  
  16. // Start of xml
  17. echo '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel>' .
  18. '<title>Instagram feed</title>' .
  19. '<link>https://browse-tutorials.com</link>' .
  20. '<description>PHP: Instagram to RSS feed</description>' .
  21. '<atom:link href="https://browse-tutorials.com/rss.xml" rel="self" type="application/rss+xml" />';
  22.  
  23. while ((int) $has_next_page === 1 and $count <= $limit) {
  24. // Append page id when not first page.
  25. $url = $instagramJsonUrl;
  26. if ($end_cursor !== null) {
  27. $url .= '&max_id=' . $end_cursor;
  28. }
  29.  
  30. // Instagram feed download and decode.
  31. $instagram = json_decode(file_get_contents($url), true);
  32.  
  33. // Save variables for while loop.
  34. $has_next_page = $instagram['user']['media']['page_info']['has_next_page'];
  35. $end_cursor = $instagram['user']['media']['page_info']['end_cursor'];
  36.  
  37. // Print current items.
  38. foreach ($instagram['user']['media']['nodes'] as $item) {
  39. echo '<item>'.
  40. '<title>' . $item['id'] . '</title>' .
  41. '<link>https://www.instagram.com/p/' . $item['code'] . '</link>' .
  42. '<description><![CDATA[' . $item['caption'] . ']]></description>' .
  43. '<pubDate>' . date(DATE_RSS, $item['date']) . '</pubDate>' .
  44. '<guid>' . $item['id'] . '</guid>' .
  45. '<enclosure url="' . $item['thumbnail_src'] . '" length="" type="image/jpeg"/>' .
  46. '</item>';
  47. }
  48.  
  49. // Increase counter for limit.
  50. ++$count;
  51. }
  52.  
  53. echo '</channel></rss>';
  54.  
Programming Language: PHP