下面是我如何从外部rss提要获取图像以及链接和帖子标题。
<div class="row">
<?php
/*
* Get latest blog entries from RSS feed blog
* Sort the entries by published date
* Get Featured Image SRC and ALT attributes using Regexp
* Loop and repeat it 4 times, to display 4 articles
*/
$feed = \'https://www.somewpsite.com/feed/\';
$entries = array();
$xml = simplexml_load_file($feed);
$entries = array_merge($entries, $xml->xpath("//item"));
//Sort feed entries by pubDate
usort($entries, function ($feed1, $feed2) {
return strtotime($feed2->pubDate) - strtotime($feed1->pubDate);
});
?>
<?php
$counter = 0;
foreach ($entries as $entry) {
//get Featured Image
//Enter entry blog Content
$blogContent = $entry->description;
//regexp to find img attribute
preg_match(\'/(<img[^>]+>)/i\', $blogContent, $matches);
//store the first img to var
$featuredImage = $matches[0];
//Get src attr with regexp
preg_match(\'@src="([^"]+)"@\', $featuredImage, $getSrc);
//Get alt attr with regexp
preg_match(\'@alt="([^"]+)"@\', $featuredImage, $getAlt);
//Store the filtered Attributes to display them.
$imgAlt = array_pop($getAlt);
$imgSrc = array_pop($getSrc);
// remove url parameters
$url = $entry->link;
$url = strtok($url, \'?\');
//Set counter to iterate over 4 items and then stop the loop.
if ($counter <= 3) { ?>
<div class="col-12 col-sm-12 col-md-6 col-lg-3 col-xl-3">
<div class="imgContainer">
<a href="<?php echo $url ?>">
<img src="<?php echo $imgSrc ?>" alt="<?php echo $imgAlt; ?>" class="img-fluid">
</a>
</div>
<h4>
<a class="blog-entry-link" href="<?php echo $url ?>"><?= $entry->title ?></a>
</h4>
</div>
<?php
$counter++;
} // end counter condition
}// end for loop ?>
</div>