make your own Reddit browser

Reddit exposes all their subreddits (and just about everything else too), to public RSS feeds. This means you can do all sorts of fun automation with it.

Here's a quick recipe to get it up and running on standard shared LAMP hosting, such as you might have for a WordPress.

[ DISCLAIMER ] - it is against Reddit terms of service to monetize these feeds in any way, although you can apply for licenses to do it. This type of service is intended as a convenience.

Your PHP file:

This takes a single string from the ajax request, representing the subreddit you want to retrieve.


<?php

$response = new stdClass();
$response->success = false;

$json = file_get_contents('php://input');
$obj = json_decode($json);

if( $obj ){

	$feed_url = 'https://reddit.com/r/' . $obj->feed . '.rss';

	$xml = simplexml_load_file( $feed_url ) or die("Error: Cannot create object");

	$response->data = $xml;

	$response->success = true;

}

echo json_encode( $response );

And, your javascript file:

This is just two big functions

One to send the request, fetch

and one to render the response to a div of your choice add_xml_entry


const siteURL = 'YOURSITE-URL'



function fetch_subreddit( subreddit ){

	fetch( siteURL + '/YOUR-PHP-SCRIPT.php', {
		method: 'post',
		headers: {
			'Content-Type': 'application/json'
		},
		body: JSON.stringify({
			feed: subreddit
		})
	})
	.then( res =>{
		res.json()
		.then( r =>{
			if( r.success ){
				for( const entry of r.data.entry ){
					add_xml_entry( entry )
				}
			}else{
				console.log('failed to parse')
			}
		})
		.catch( error =>{
			console.log( error )
		})
	})
	.catch( err =>{
		console.log( err )
	})

}




function add_xml_entry( entry ){

	const entry = document.createElement('div')
	entry.classList.add('rss-entry')
	entry.innerHTML += `<div class="rss-title">${ entry.title }</div>`

	const hidden_content = document.createElement('div')
	hidden_content.classList.add('rss-hidden')
	hidden_content.innerHTML += `${ JSON.stringify(entry.author)}<br>`
	hidden_content.innerHTML += entry.content

	entry.appendChild( hidden_content )

	document.getElementById('YOUR-DISPLAY-ELEMENT').appendChild( div )

}


// run it !
// fetch_subreddit( 'gamedev' )



Leave a Reply

Your email address will not be published. Required fields are marked *

oko
friend