okuden-labo
2/1/2017 - 8:52 AM

RSSの取得と表示[phpで表示]

RSSの取得と表示[phpで表示]

<?php
  //参考サイト:https://syncer.jp/php-how-to-get-feed
  //利用したサイト http://www.idnet821.jp/
  //同じドメインだとjqueryだけで取得して完結するが、件数を指定したり、別ドメインのものを読み込む場合は、phpを使う。

	// rss-phpライブラリの読み込み(https://github.com/dg/rss-php)
	require_once "./Feed.php" ;

	// 取得するフィードのURLを指定
	$url = "http://exampledomain.com" ;

	// インスタンスの作成
	$feed = new Feed ;

	// RSSを読み込む
	$rss = $feed->loadRss( $url ) ;

	// HTML表示用
	$html = '' ;

	foreach( $rss->item as $item )
	{
		// 各エントリーの処理
		$title = $item->title ;	// タイトル
		$link = $item->link ;	// リンク
		$description = $item->description ;	// 詳細

		// 日付の取得(UNIX TIMESTAMP)
		foreach( array( "pubDate" , "date_timestamp" , "dc:date" , "published" , "issued" ) as $time )
		{
			if( isset( $item->{ $time } ) && !empty( $item->{ $time } ) )
			{
				$timestamp = ( is_int( $item->{ $time } ) ) ? $item->{ $time } : strtotime( $item->{ $time } ) ;
				break ;
			}
		}

		// 仮に日付が取得できなかったらとりあえず現在時刻でも…(笑)
		if( !isset( $timestamp ) )
		{
			$timestamp = time() ;
		}

		// 表示
		$html .= '<li><a href="' . $link . '" target="_blank">' . $title . '</a></li>' ;
	}
?><!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="robots" content="noindex,nofollow">

		<!-- ビューポートの設定 -->
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<style>
		div#feed ul{
	font-size: 12px;
	list-style-type: none;
	line-height: 1.8;
	padding-left: 0;
}
</style>
	</head>
<body>
<div id="feed">
<ul>
<?php echo $html ?>
</ul>
</div>

</body>
</html>