How to create a simple RSS Reader in PHP
Learn how to create a simple RSS reader that allows to load the XML feed from URL to your website.
Implementation
To implement RSS Reader in my web application, I just need to utilize the XMLReader
object provided in PHP by default. Load XML feed from the URL, iterate through the elements in the document, create a collection of data and return it to the clients.
namespace FM\Integrations;
use XMLReader;
use SimpleXMLElement;
class ESPN
{
public function read(): array
{
$data = [];
$reader = new XMLReader();
$reader->open('https://www.espn.co.uk/espn/rss/football/news');
while ($reader->read()) {
if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'item') {
$item = new SimpleXMLElement($reader->readOuterXML(), LIBXML_NOCDATA);
if (! empty($item->title) && ! empty($item->link)) {
$data[] = [
'title' => (string) $item->title,
'url' => (string) $item->link,
'description' => ! empty($item->description) ? (string) $item->description : '',
];
}
}
}
$reader->close();
return $data;
}
}
It's important to note that I'm not striving for perfection here. It's a prototype intended to show the basic idea, which can be refined over time so for now I don't address security issues related to loading external resources. However, if I were developing a production-ready solution, it would be essential to pay more attention to that aspect.
Now, I just need to create a new instance and use get
function for querying the data. I'm using separated get
function, because I woudl like to separate data extraction process from returning results and maybe filtering them in the future.
Links
Looking for a developer who
truly cares about your business?
My team and I provide expert consultations, top-notch coding, and comprehensive audits to elevate your success.
Feedback
How satisfied you are after reading this article?