Best way to parse RSS/Atom feeds with PHP
Relying on third-party libraries like MagpieRSS is a common pattern, but as you've likely encountered, they often struggle when feed authors deviate from standards or include malformed XML. When a library "falls over" on a slightly broken feed, it throws exceptions that clutter your logs and disrupt your scraping pipeline. The most robust approach isn't to find another wrapper library, but to handle the parsing manually using PHP's built-in capabilities combined with strict error handling. This shifts the burden of validation from an external dependency to your own code, giving you precise control over how failures are managed.
PHP provides SimpleXMLElement and DOMDocument, both of which are capable of parsing XML without any external packages. However, the standard simplexml_load_string() function will throw a SimpleXMLElement exception if the XML is invalid. To build a resilient parser, you must wrap this call in a try-catch block. This allows your application to log a warning about a specific feed URL being malformed and continue processing the rest of your queue, rather than crashing the entire script.
$feedUrl = 'https://example.com/feed';
$xmlString = file_get_contents($feedUrl);
if ($xmlString === false) {
// Handle network error or timeout gracefully
return ['error' => 'Could not fetch feed'];
}
try {
$xml = simplexml_load_string($xmlString, 'SimpleXMLElement', LIBXML_NOCDATA);
if ($xml === null) {
return ['error' => 'Invalid XML structure'];
}
// Proceed with parsing items
foreach ($xml->channel->item as $item) {
// Process $item
}
} catch (Exception $e) {
// Log the specific error for debugging
error_log("Failed to parse feed: " . $e->getMessage());
}
The real challenge with RSS and Atom, however, lies in the fact that they are not strictly standardized. An RSS 2.0 feed might define items inside <channel><item>, while a custom or poorly generated feed might nest them differently, or an Atom feed might use <entry> instead of <item>. A rigid parser will break instantly if it assumes a specific structure. The solution is to inspect the root element first and then traverse dynamically based on what is actually present in the document.
For Atom feeds specifically, you must check for the presence of xmlns namespaces. Unlike RSS, which historically avoided namespaces, Atom relies heavily on them (e.g., atom:title, atom:link). If your parser blindly accesses $xml->title, it will fail on an Atom feed where the title is located at $xml->entry->title. You need to write logic that detects the feed type by checking for unique identifiers or structural markers, then adjusts the navigation path accordingly.
$rootElement = strtolower($xml->getName());
$isAtom = ($rootElement === 'feed' || strpos((string)$xml['xmlns'], 'atom') !== false);
if ($isAtom) {
$items = $xml->xpath('//entry');
} else {
$items = $xml->channel->item;
}
Using XPath queries is often cleaner than deep nesting checks because it allows you to search for specific elements regardless of their depth in the tree. This flexibility is crucial when dealing with non-standard feeds. It also means you don't have to maintain a list of every possible library that "works" on broken XML; instead, your code simply handles whatever the XML parser returns.
If you are building this within the Laravel ecosystem, consider leveraging existing community packages like rss-parser or spatie/atom-feed-parser. While these offer convenience, they still rely on underlying parsers and may exhibit similar fragility if the source feed changes drastically. The manual approach using DOMDocument remains the gold standard for production systems requiring high availability.
One final pitfall is memory usage. Loading massive feeds into a single SimpleXMLElement object can spike memory consumption. For very large datasets, switching to DOMDocument allows you to load the XML in fragments or process it as a stream if necessary, though for most web scraping tasks, simple error wrapping around simplexml_load_string offers the best balance of readability and resilience.
