RSS フィードを使用しているときに simplepie に画像のみを表示する方法 simplepie を使用していますが、rss から画像のみを抽出できるようにします。
2 に答える
特定のフィード構造が異なることを考えると、私が知っている明示的な方法はありません。これが私がそれを行うことができた方法です。まずこの記事をチェックしてください:
SimplePie を使用して WordPress RSS フィードからサムネイルを表示する方法は?
コードをコピーして貼り付け、いくつかの小さな変更を加えることができました
私はWordpressを使用していませんでしたが、何をする必要があるかを知るのに役立ちました.
このコードを feed->init(); の後に挿入します。
//This function will get an image from the feed
function returnImage ($text) {
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
$pattern = "/<img[^>]+\>/i";
preg_match($pattern, $text, $matches);
$text = $matches[0];
return $text;
}
//This function will filter out image url which we got from previous returnImage() function
function scrapeImage($text) {
$pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/';
preg_match($pattern, $text, $link);
$link = $link[1];
$link = urldecode($link);
return $link;
}
ここで関数を呼び出して、説明 (私の場合はコンテンツ) を検索して img タグを見つけ、出力を正しく構造化します。これは私のコードがどのように見えるかです:
foreach ($feed->get_items(0 , 3) as $item):
$feedDescription = $item->get_content();
$image = returnImage($feedDescription);
$image = scrapeImage($image);
$image_url= $item->get_permalink();
$description = $item->get_description();
?>
<div class="item">
<h4><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h4>
<div class="image-box"><?php echo '<a href="' . $image_url . '"><img src="' . $image . '" /></a>'."\n";?></div>
<p><?php echo $description ?></p>
<p><a href="<?php echo $item->get_permalink(); ?>">Continue Reading</a></p>
</div>
<?php endforeach; ?>
バグが発生する可能性がありますが、フィード内の img タグが存在する場所がわかれば、simplepie を取得してフィードを解析すると、関数がタグとフォーマットを見つけて HTML の準備が整います。
1 つの投稿だけをプルするには、ループを編集できます。
foreach ($feed->get_items(0 , 1) as $item):
最初の数字 (0) が開始点で、0 が最新の投稿です。2 番目の数字 (1) は、プルする投稿の数です。必要な画像は 1 つだけなので、その数を 1 にします。
たぶん、クライアント側でそれをやりたいと思うでしょう。次に、jQuery を使用すると非常に簡単です。JavaScript の項目コンテンツが次のようになっているとします。
var content = '<div><a href="http://kwout.com/cutout/b/es/y2/ukn_rou_sha.jpg"
imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;">
<img border="0" height="239" src="http://kwout.com/cutout/b/es/y2/ukn_rou_sha.jpg"
width="320"></a>Erat austro rerum.</div>';
次に、jQuery セレクターを使用して、コンテンツ内の画像を簡単に識別して分離できます。たとえば使用
$(content).find('img:first'); //find the FIRST image inside an element or
$(content).find('a:first'); //take the hyperlink AND the image
コンテンツ内の最初の画像ではない場合、またはコンテンツがこの例よりも複雑な場合 (ほとんど ;-) - 心配する必要はありません - 他のセレクターがそのトリックを実行します。詳細については、jquery.com のドキュメントを参照してください。
このようにして、要素を削除したり、コンテンツ内のさまざまな要素にいくつかのクラスを追加したり、クラスを追加したりして、投稿を自分のやり方で表示しました。