I have the following code:
function parse() {
$content = file_get_contents($this->feed);
$rss = new SimpleXmlElement($content);
$rss_split = array();
$i = 0;
foreach ($rss->channel->item as $item) {
$title = (string) $item->title; // Title
$link = (string) $item->link; // Url Link
$content = $item->children('content', true)->encoded;
preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $content, $image);
$image = substr($image['src'], 0, strpos($image['src'], '"'));
$rss_split[$i]['title'] = $title;
$rss_split[$i]['link'] = $link;
$rss_split[$i]['image'] = $image;
$i++;
}
return $rss_split;
}
Here, $this->feed contains the RSS feed’s URL. The problem is I do not know how to validate the URL to be sure it is a valid RSS feed.
To verify that it is XML:
Once you have verified that it is XML you have a couple of options:
isset($rss->channel->item)existed and$rss->channel->item->count()> 0.count($rss->xpath(/channel/item)) > 0.I’d use xpath, personally as I find it a little more obvious when reading the code.
SIDE NOTE:
Seriously? You’ve already got XML object. Why are you using RegEx?
Don’t do this:
When this is a valid option: