Computer/PHP

RSS 읽어서 뉴스 뿌려주기

알찬돌삐 2004. 11. 29. 04:15
PEAR의 RSS 패키지를 이용해서 아~주 간단하게 만들어 봤습니다.
newschannel.txt 파일에 있는 채널목록을 읽어서 해당 채널의 뉴스를 가져옵니다.
리프레시시간내에 있으면 캐시파일로 부터 읽어오고, 아니면 새로 캐시파일을 생성합니다.

구현물은 http://fguy.com/index.php?module=news 에서 보실 수 있습니다.

[CODE] <?php // 가져온 뉴스 중 몇개까지 보여줄건지.. define("PAGE_LIMIT", 100); // 날짜 형태 define("DATE_FORMAT", "Y/m/d H:i:s"); // 리프레시 시간 (분) define("REFRESH_MINUTE", 2); $lastmodified = get_last_modified_time(); // 리프레시 시간 내에 있으면 cache hit if(time() - $lastmodified < REFRESH_MINUTE * 60 && file_exists("currentnews.html")) { $contents = trim(file("currentnews.html")); echo $contents; } else { require_once "RSS.php"; // url_fopen 허용 if (ini_get("allow_url_fopen") == 0) { ini_set("allow_url_fopen", 1); } $news = array(); $channel_list = array(); // 채널 목록을 읽어온다. $fd = fopen ("newschannel.txt", "r"); while (!feof ($fd)) { $channel_list[] = trim(fgets($fd, 4096)); } fclose ($fd); // 각 채널에서 뉴스를 읽어온다. foreach($channel_list as $rss_url) { if(PEAR::isError($r =& new XML_RSS($rss_url))) continue; $r->parse(); /* keys :title, link, description, dc:date (or pubdate) */ $channel_info = array(); foreach($r->getChannelInfo() as $key => $val) { $channel_info["cp_" . $key] = $val; } foreach ($r->getItems() as $value) { array_change_key_case($value, CASE_LOWER); $tmp_arr = array_merge($value, $channel_info); if($tmp_arr["dc:date"]) $tmp_arr[date] = $tmp_arr["dc:date"]; else if($tmp_arr["pubdate"]) $tmp_arr[date] = $tmp_arr["pubdate"]; // unix timestamp를 키로 한다. $key = strtotime($tmp_arr[date]); $tmp_arr[date] = date(DATE_FORMAT, $key); // 키가 중복되지 않도록.... while(array_key_exists($key,$news)) { $key--; } if($tmp_arr[description]) $tmp_arr[description] = parse_description($tmp_arr[description]); $news[$key] = $tmp_arr; } } // 시간의 역순으로 정렬 krsort($news, SORT_NUMERIC); $k = 0; // 뉴스 아이템을 화면에 출력한다. foreach($news as $item) { $k++; // 제한 갯수 까지만 보여준다 if($k > PAGE_LIMIT) break; ?> <!-- 뉴스 아이템 --> <li><a href="<?= $item[link] ?>"><?= $item[title] ?></a> (<?= $item[date] ?>) [<?= $item[cp_title] ?>] <p> <?= $item[description] ?> </li> <!-- 뉴스 아이템 끝 --> <? } unset($news); set_modified($tpl->get()); } // description 교정 function parse_description($body) { $current = array( "<a href=" ); $target = array( "<a target=\"_blank\" href=" ); $body = str_replace($current, $target, $body); return $body; } // 마지막 수정 시간 function get_last_modified_time() { $lastmodifiedtime = 0; if(file_exists("newslastmodifiedtime.txt")) { $lastmodifiedtime = trim(file("newslastmodifiedtime.txt")); } return $lastmodifiedtime; } // 수정 내역 반영 function set_modified($contents) { $fd = fopen ("newslastmodifiedtime.txt", "w"); fwrite($fd, time()); fclose ($fd); $fd = fopen ("currentnews.html", "w"); fwrite($fd, $contents); fclose ($fd); } ?> [/CODE]

원 글 보기


.

'Computer > PHP' 카테고리의 다른 글

PHP를이용한다중연결소켓통신2  (0) 2005.03.20
PHP를이용한다중연결소켓통신1  (0) 2005.03.20
네이버에 올라온 거 심심해서 만들어봄...  (47) 2005.03.13
정규 표현식  (0) 2004.11.29
Linux Commender  (0) 2004.11.29