Skip to content

Instantly share code, notes, and snippets.

@BlackScorp
Created April 8, 2022 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BlackScorp/dac98387730f229776b26582dbeab263 to your computer and use it in GitHub Desktop.
Save BlackScorp/dac98387730f229776b26582dbeab263 to your computer and use it in GitHub Desktop.
<?php
error_reporting(E_ALL);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36\r\n"
]
]);
$xml = file_get_contents("https://dev.to/feed/tag/php",false,$context);
final class RSSItem
{
public function __construct(
public readonly string $title,
public readonly string $creator,
public readonly DateTimeInterface $pubDate,
public readonly string $link,
public readonly string $guid,
public readonly string $description,
public readonly array $category
) {
}
}
$domDocument = new DOMDocument();
$domDocument->loadXML($xml);
$xpath = new DOMXPath($domDocument);
$items = $xpath->query('/rss/channel/item');
$rssItems = [];
/** @var DOMNode $item */
foreach($items as $item){
$variables = [];
foreach($item->childNodes as $childNode){
if (!$childNode instanceof DOMElement) {
continue;
}
$tagName = str_replace($childNode->prefix.':','',$childNode->tagName);
if($tagName === 'pubDate'){
$variables[$tagName] = new DateTimeImmutable($childNode->nodeValue);
continue;
}
if($tagName === 'category'){
$variables[$tagName][] = $childNode->nodeValue;
continue;
}
$variables[$tagName] = $childNode->nodeValue;
}
$rssItems[]= new RSSItem(...$variables);
}
var_dump($rssItems);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment