올블로그(http://www.allblog.net/Home/) 명예의 전당글 가져오기 > 개발자팁

개발자팁

개발과 관련된 유용한 정보를 공유하세요.
질문은 QA에서 해주시기 바랍니다.

올블로그(http://www.allblog.net/Home/) 명예의 전당글 가져오기 정보

기타 올블로그(http://www.allblog.net/Home/) 명예의 전당글 가져오기

본문

안녕하세요 유창화입니다.

제가 항상 생각하고 또 생각하는 것은
'용도에 알맞는 도구를 사용하여야 한다.'
라는 부분입니다.

요새 rss 주소만 알면 글들을 쉽게 내 홈페이지에 달수 있습니다.
rss 를 읽어오는데 꼭 rss reader 처럼 포괄적인것으로 읽어올 필요는 없습니다.
rss도 버젼이 다양하고, 보여주는 쪽에서 규칙외에 부분으로 보여주는 경우도 있기 때문에
기존 rss reader 들이 덩어리가 커지고 그렇습니다.

단순히 현재의 rss의 정보를 읽어서 그것을 적당히 보여주는 것이 목적이라면
다음과 같이 하여도 됩니다.

보여주는 모양새는 한rss ( http://www.hanrss.com/ )를 참조햇습니다.

--------------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Rss 읽어오기</title>
<style>
body {margin:0px 10px 3px 10px;padding:0}
body,td,select {font-family:Verdana,Gulim;font-size:9pt;}
td {overflow:hidden;text-overflow:ellipsis;}
td.description p {margin:0;padding:3 0 3 0;}
a.lnk1:link,a.lnk1:visited,a.lnk1:hover {color:#0000ff;text-decoration:underline;}
a.lnk2:link,a.lnk2:visited {color:#808080;text-decoration:none;}
a.lnk2:hover {text-decoration:underline;}
a.lnk3:link {color:#0000ff;text-decoration:none;}
a.lnk3:visited {color:#800080;text-decoration:none;}
a.lnk3:hover {text-decoration:underline;}
a.lnk4:link,a.lnk4:visited {color:#D2691E;text-decoration:none;}
a.lnk4:hover {text-decoration:underline;}
a.lnk5:link,a.lnk5:visited {color:#0000ff;text-decoration:none;}
a.lnk5:hover {background-color:#eeeeee;}
.header1 {font-weight:bold;font-size:12pt;}
.btn_submit1 {border:1px solid gray;width:40;height:20;background-color:white;font-family:Gulim;font-size:9pt;padding:2 0 0 0}
.btn_submit2 {border:1px solid #c0c0c0;width:34;height:18;background-color:white;font-family:Gulim;font-size:8pt;line-height:12pt}
</style>
<base target=_blank>
</head>
<body bgcolor='#ffffff'>
<?php

//올블로그 명예의전당 rss 글내용이 하루에 한번만 바뀝니다.
$url = "http://www.allblog.net/Rss/BestPosts.xml";

$result = file($url);
$text = implode("\n", $result);

if(!empty($text)){ 
 
  $item = explode("<item>", $text);
  $count = count($item);

  echo "
<table width=100% border=0 cellpadding=0 cellspacing=0 style=\"table-layout:fixed;\">
<tr><td>
<table width=100% border=0 cellpadding=0 cellspacing=0 style=\"table-layout:fixed;\">
<tr>
<td align=right valign=top style=\"padding:0 4 0 0;font-size:8pt;color:gray\" nowrap>총 <b>" . ($count - 1) . "</b>개&nbsp;&nbsp;|&nbsp;&nbsp;최종업데이트: " . date("Y-m-d H:i") . "</td>
</tr>
</table>

</td></tr>
<tr><td height=4></td></tr>
</table>
  ";

  if (is_array($item) && count($item) > 1) {

    for ($i = 1; $i < $count; $i++){

      preg_match_all("`<title>(.+)</title><link>(.+)</link><source url=\".+\">(.+)</source><category>([^<]+)</category>(<category>([^<]+)</category>)?(<category />)?<pubDate>(.+)</pubDate><description><!\[CDATA\[(.+)\]\]></description>`s", $item[$i], $matches);

      if (is_array($matches[1]) && count($matches[1]) > 0) {

        foreach($matches[1] as $key => $val){

          $title = (!empty($val)) ? $val : '';
          $link = (!empty($matches[2][$key])) ? $matches[2][$key] : '';
          $source = (!empty($matches[3][$key])) ? $matches[3][$key] : '';
          $category1 = (!empty($matches[4][$key])) ? $matches[4][$key] : '';
          $category2 = (!empty($matches[6][$key])) ? $matches[6][$key] : '';
          $category = (!empty($category1) && !empty($category2)) ? $category1 . ", " . $category2 : $category1 . $category2;
          $pubDate = (!empty($matches[8][$key])) ? date("Y-m-d H:i", strtotime($matches[8][$key])) : '';
          $description = (!empty($matches[9][$key])) ? $matches[9][$key] : '';
          $description_len = number_format(strlen($description));

          if (!preg_match("`(<\s*\t*img\s*\t*|<\s*\t*a\s*\t*href)`i", $description)) $description = strip_tags(str_replace(array("&lt;", "&gt;", "<br /><hr />위 내용은 올블로그가 올블로그에 등록한 블로그로부터 수집하여 서버에 저장하고 있는 내용의 전체 또는 일부 입니다. 이 게시물에 대한 모든 저작권과 책임은 해당 블로그의 등록자에게 있습니다."), array("<", ">", ""), $description)) . "<br /><hr />위 내용은 올블로그가 올블로그에 등록한 블로그로부터 수집하여 서버에 저장하고 있는 내용의 전체 또는 일부 입니다. 이 게시물에 대한 모든 저작권과 책임은 해당 블로그의 등록자에게 있습니다.";

          echo "
<a href=\"" . $link . "\"></a>
<table width=100% border=0 cellpadding=0 cellspacing=0>
<tr><td bgcolor=#bdb76b><img width=1 height=1 alt=\"\"></td></tr>
<tr><td bgcolor=#ebebd5 style='padding:5 2 6 2'>
  <table width=100% border=0 cellpadding=0 cellspacing=0>
  <tr><td style=\"font-size:10pt\"><a href=\"" . $link . "\"><span style=\"font-weight:bold\">" . $title . "</span></a></td></tr>
  </table>
</td></tr>
<tr><td style='padding:4 2 0 2'>
  <table width=100% border=0 cellpadding=0 cellspacing=0>
  <tr><td style='font-size:8pt;'> <font color=#808080>" . $pubDate . " 작성 <font color=#808080>| " . $category . "</font> <font color=#808080>| " . $description_len . "byte</font></font></td><td align=right style=\"font-family:Gulim;font-size:8pt;\" nowrap>&nbsp;</td></tr>
  </table>
</td></tr>
</table>
<table id=\"desc_9612007\" width=100% border=0 cellpadding=0 cellspacing=0>
<tr><td style='padding:6 2 0 2;line-height:14pt;' class=description>" . $description . "</td></tr>
<tr><td height=10></td></tr>
</table>
<table width=100% border=0 cellpadding=0 cellspacing=0><tr><td height=12></td></tr></table>
          ";
        }
      }
    }
  }
}

?>
</body>
</html>
--------------------------------------------------------------------------------------------------------------------------------------

여기에 캐쉬기능만 달면 올블로그 전용으로는 가벼운 리더기가 될수 있습니다.

참고 url http://search.dyd.cc/simplereader.php<div class='small'>[이 게시물은 관리자님에 의해 2011-10-31 17:12:10 PHP & HTML에서 이동 됨]</div>
추천
0

댓글 17개

아래의 내용은 간단하게 캐쉬 기능을 추가했습니다.

--------------------------------------------------------------------------------------------------------------------------------------------------------------
<?php

//캐쉬기능추가
//1. 이파일과 동일한 경로에 cashe 라는 디렉토리를 생성한다.
//2. 퍼미션은 777로 준다.
$cashe_time = '10';//분단위, 숫자만
$cashe_dir = 'cashe';// /를 뺀 순수한 디렉토리명만
$cashe_file = preg_replace("`^(.*)(/[^/]+)$`", "\\1/" . $cashe_dir . "\\2", __FILE__);
if (!is_dir("./" . $cashe_dir)) {

  echo "캐쉬 디렉토리가 존재하지 않습니다.";
  exit;
}

//캐쉬 파일이 존재하고, 수정된 시간이 지정된 시간을 넘지 않았을 경우 인클루드 후 종료
if (is_file($cashe_file) && (filemtime ($cashe_file) + ($cashe_time * 60) > time())){

  include $cashe_file;
  exit;
}

ob_start();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Rss 읽어오기</title>
<style>
body {margin:0px 10px 3px 10px;padding:0}
body,td,select {font-family:Verdana,Gulim;font-size:9pt;}
td {overflow:hidden;text-overflow:ellipsis;}
td.description p {margin:0;padding:3 0 3 0;}
a.lnk1:link,a.lnk1:visited,a.lnk1:hover {color:#0000ff;text-decoration:underline;}
a.lnk2:link,a.lnk2:visited {color:#808080;text-decoration:none;}
a.lnk2:hover {text-decoration:underline;}
a.lnk3:link {color:#0000ff;text-decoration:none;}
a.lnk3:visited {color:#800080;text-decoration:none;}
a.lnk3:hover {text-decoration:underline;}
a.lnk4:link,a.lnk4:visited {color:#D2691E;text-decoration:none;}
a.lnk4:hover {text-decoration:underline;}
a.lnk5:link,a.lnk5:visited {color:#0000ff;text-decoration:none;}
a.lnk5:hover {background-color:#eeeeee;}
.header1 {font-weight:bold;font-size:12pt;}
.btn_submit1 {border:1px solid gray;width:40;height:20;background-color:white;font-family:Gulim;font-size:9pt;padding:2 0 0 0}
.btn_submit2 {border:1px solid #c0c0c0;width:34;height:18;background-color:white;font-family:Gulim;font-size:8pt;line-height:12pt}
</style>
<base target=_blank>
</head>
<body bgcolor='#ffffff'>
<?php

//올블로그 명예의전당 rss 글내용이 하루에 한번만 바뀝니다.
$url = "http://www.allblog.net/Rss/BestPosts.xml";

$result = file($url);
$text = implode("\n", $result);

if(!empty($text)){ 
 
  $item = explode("<item>", $text);
  $count = count($item);

  echo "
<table width=100% border=0 cellpadding=0 cellspacing=0 style=\"table-layout:fixed;\">
<tr><td>
<table width=100% border=0 cellpadding=0 cellspacing=0 style=\"table-layout:fixed;\">
<tr>
<td align=right valign=top style=\"padding:0 4 0 0;font-size:8pt;color:gray\" nowrap>총 <b>" . ($count - 1) . "</b>개&nbsp;&nbsp;|&nbsp;&nbsp;최종업데이트: " . date("Y-m-d H:i") . "</td>
</tr>
</table>

</td></tr>
<tr><td height=4></td></tr>
</table>
  ";

  if (is_array($item) && count($item) > 1) {

    for ($i = 1; $i < $count; $i++){

      preg_match_all("`<title>(.+)</title><link>(.+)</link><source url=\".+\">(.+)</source><category>([^<]+)</category>(<category>([^<]+)</category>)?(<category />)?<pubDate>(.+)</pubDate><description><!\[CDATA\[(.+)\]\]></description>`s", $item[$i], $matches);

      if (is_array($matches[1]) && count($matches[1]) > 0) {

        foreach($matches[1] as $key => $val){

          $title = (!empty($val)) ? $val : '';
          $link = (!empty($matches[2][$key])) ? $matches[2][$key] : '';
          $source = (!empty($matches[3][$key])) ? $matches[3][$key] : '';
          $category1 = (!empty($matches[4][$key])) ? $matches[4][$key] : '';
          $category2 = (!empty($matches[6][$key])) ? $matches[6][$key] : '';
          $category = (!empty($category1) && !empty($category2)) ? $category1 . ", " . $category2 : $category1 . $category2;
          $pubDate = (!empty($matches[8][$key])) ? date("Y-m-d H:i", strtotime($matches[8][$key])) : '';
          $description = (!empty($matches[9][$key])) ? $matches[9][$key] : '';
          $description_len = number_format(strlen($description));

          if (!preg_match("`(<\s*\t*img\s*\t*|<\s*\t*a\s*\t*href)`i", $description)) $description = strip_tags(str_replace(array("&lt;", "&gt;", "<br /><hr />위 내용은 올블로그가 올블로그에 등록한 블로그로부터 수집하여 서버에 저장하고 있는 내용의 전체 또는 일부 입니다. 이 게시물에 대한 모든 저작권과 책임은 해당 블로그의 등록자에게 있습니다."), array("<", ">", ""), $description)) . "<br /><hr />위 내용은 올블로그가 올블로그에 등록한 블로그로부터 수집하여 서버에 저장하고 있는 내용의 전체 또는 일부 입니다. 이 게시물에 대한 모든 저작권과 책임은 해당 블로그의 등록자에게 있습니다.";

          echo "
<a href=\"" . $link . "\"></a>
<table width=100% border=0 cellpadding=0 cellspacing=0>
<tr><td bgcolor=#bdb76b><img width=1 height=1 alt=\"\"></td></tr>
<tr><td bgcolor=#ebebd5 style='padding:5 2 6 2'>
  <table width=100% border=0 cellpadding=0 cellspacing=0>
  <tr><td style=\"font-size:10pt\"><a href=\"" . $link . "\"><span style=\"font-weight:bold\">" . $title . "</span></a></td></tr>
  </table>
</td></tr>
<tr><td style='padding:4 2 0 2'>
  <table width=100% border=0 cellpadding=0 cellspacing=0>
  <tr><td style='font-size:8pt;'> <font color=#808080>" . $pubDate . " 작성 <font color=#808080>| " . $category . "</font> <font color=#808080>| " . $description_len . "byte</font></font></td><td align=right style=\"font-family:Gulim;font-size:8pt;\" nowrap>&nbsp;</td></tr>
  </table>
</td></tr>
</table>
<table id=\"desc_9612007\" width=100% border=0 cellpadding=0 cellspacing=0>
<tr><td style='padding:6 2 0 2;line-height:14pt;' class=description>" . $description . "</td></tr>
<tr><td height=10></td></tr>
</table>
<table width=100% border=0 cellpadding=0 cellspacing=0><tr><td height=12></td></tr></table>
          ";
        }
      }
    }
  }
}

?>
</body>
</html>
<?php

$save_text = ob_get_contents();
ob_end_clean();

//캐쉬파일로 저장
$fp = @fopen($cashe_file, 'w');

if (empty($fp)) {

  echo "캐쉬 디렉토리의 퍼미션을 확인하세요";
  exit;
}

@fwrite($fp, $save_text);
@fclose($fp);
@chmod($cashe_file, 0777);

//출력
echo $save_text;

?>
여기서 사용된 캐쉬 부분은 다른 부분에도 응용하여 사용할수 있습니다.

형식은 아래와 같습니다.

-----------------------------------------------------------------------------------------------------
<?php

//캐쉬기능추가
//1. 이파일과 동일한 경로에 cashe 라는 디렉토리를 생성한다.
//2. 퍼미션은 777로 준다.
$cashe_time = '10';//분단위, 숫자만
$cashe_dir = 'cashe';// /를 뺀 순수한 디렉토리명만
$cashe_file = preg_replace("`^(.*)(/[^/]+)$`", "\\1/" . $cashe_dir . "\\2", __FILE__);
if (!is_dir("./" . $cashe_dir)) {

  echo "캐쉬 디렉토리가 존재하지 않습니다.";
  exit;
}

//캐쉬 파일이 존재하고, 수정된 시간이 지정된 시간을 넘지 않았을 경우 인클루드 후 종료
if (is_file($cashe_file) && (filemtime ($cashe_file) + ($cashe_time * 60) > time())){

  include $cashe_file;
  exit;
}

ob_start();

?>
파일의 실제 내용
<?php

$save_text = ob_get_contents();
ob_end_clean();

//캐쉬파일로 저장
$fp = @fopen($cashe_file, 'w');

if (empty($fp)) {

  echo "캐쉬 디렉토리의 퍼미션을 확인하세요";
  exit;
}

@fwrite($fp, $save_text);
@fclose($fp);
@chmod($cashe_file, 0777);

//출력
echo $save_text;

?>
------------------------------------------------------------------------------------------------------------------------------------------------
좋은팁 감사합니다.^^

밑천 다 떨어져간다고 하시는데.....

아직은 숨겨둔 밑천이 많이 있는걸로 사료 되므로 팍팍 풀어 주세요.ㅋㅋ
감사합니다.

늦게라도 보신다면 조언 부탁드립니다.

캐쉬 추가기능 코드로 테스트 해보았습니다.
권고 하신대로 UTF-8로 저장하고 불렀더니 아래 에러가 뜹니다.
참고 링크는 현재 잘 들어오던데, 제 서버에서 file() 함수를 막아놓은 경우인가요??

Warning: file(): URL file-access is disabled in the server configuration in /web1/gnusr/www.gnusr.com/Ysample/Yallblog_rss.php on line 56
Warning: file(http://www.allblog.net/Rss/BestPosts.xml): failed to open stream: no suitable wrapper could be found in /web1/gnusr/www.gnusr.com/Ysample/Yallblog_rss.php on line 56
Warning: implode(): Bad arguments. in /web1/gnusr/www.gnusr.com/Ysample/Yallblog_rss.php on line 57
또 다른 유창화님의 팁을 통해 위 코멘트에 붙였던 서버 설정을 피해가는 방법을 찾았습니다.^^
다시한번 유창화님께 감사의 말씀을 드립니다.

원본 - 이렇게 되면 좋은데 제 계정에서는 file()함수가 막혀있더군요.

  //올블로그 명예의전당 rss 글내용이 하루에 한번만 바뀝니다.
  // $url = "http://www.allblog.net/Rss/BestPosts.xml";
  // $result = file($url);
  // $text = implode("\n", $result);


아래는 유창화님의 리퍼러 변경관련 코멘트에서 file()함수 대체 팁을 적용해서 성공(?)한 경우입니다.
http://gnusr.com/Ysample/Yallblog_rss_utf.php

//////////////////////////////////////////////////////////////////////////
// 리퍼러,캐시콘,file()함수등 제한된 부분을 돌고돌아 겨우 가져옴
// http://www.sir.co.kr/bbs/tb.php/pl_php/182 유창화님
$url = "http://www.allblog.net/Rss/BestPosts.xml";//읽어올 url
$referer = "http://test.com/";//속일 리퍼러

$array = parse_url($url);
$url_scheme = $array['scheme'];
$url_server = $array['host'];
$url_path = $array['path'];
$url_query= $array['query'];
$url_port = (empty($array['port'])) ? 80 : $array['port'];

$fp = fsockopen($url_server, $url_port);

if (empty($fp)) {

  echo "error-http소켓접속에 실패하였습니다.";
  exit;
}

fputs($fp, "GET " . $url_path . "?" . $url_query . " HTTP/1.0\n");
fputs($fp, "Accept: */*\n");
fputs($fp, "Content-Type: application/x-www-form-urlencoded\n");
fputs($fp, "Host: $url_server:$url_port\n");
fputs($fp, "Referer: $referer\n");
fputs($fp, "Cache-control: private\n");
fputs($fp, "Pragma: no-cache\n");
fputs($fp, "Connection: close\n\n");

$xmls = '';
while (!feof($fp)){

  $xmls .= fgets($fp, 1024);
}

fclose($fp);

//$xmls = trim(substr($xmls,strpos($xmls, "\r\n\r\n")));//헤더 삭제
//echo $xmls;//제어이전 내용 확인

//////////////////////////////////////////////////////////////
// 이 서버에서는 바로 읽어서 처리는 않됨
// 캐쉬 디렉토리에 tmp.php파일 생성, 읽어온 내용 임시저장
$tmp_file = $cashe_dir . '/' . 'tmp.php';

$fp = @fopen($tmp_file, 'w');

if (empty($fp)) {
  echo "임시저장 디렉토리의 퍼미션을 확인하세요";
  exit;
}

@fwrite($fp, $xmls);
@fclose($fp);
@chmod($tmp_file, 0777);

$text = implode("\n", file($tmp_file));
// 임시저장 파일을 읽어들여 캐쉬에 저장
//echo $text;//저장 내용 확인
//////////////////////////////////////////////////// 끝
file이 외부파일을 읽어오는 데 사용할수 없을경우

fsockopen을 사용하시면 되구요.

읽어온 파일을 저장할 필욘 없고 바로 사용하면 될듯한데요.


$url = "http://www.allblog.net/Rss/BestPosts.xml";//읽어올 url
$referer = "http://www.allblog.net/";//속일 리퍼러

$array = parse_url($url);
$url_scheme = $array['scheme'];
$url_server = $array['host'];
$url_path = $array['path'];
$url_query= $array['query'];
$url_port = (empty($array['port'])) ? 80 : $array['port'];

$fp = fsockopen($url_server, $url_port);

if (empty($fp)) {

  echo "error-http소켓접속에 실패하였습니다.";
  exit;
}

fputs($fp, "GET " . $url_path . "?" . $url_query . " HTTP/1.0\n");
fputs($fp, "Accept: */*\n");
fputs($fp, "Content-Type: application/x-www-form-urlencoded\n");
fputs($fp, "Host: $url_server:$url_port\n");
fputs($fp, "Referer: $referer\n");
fputs($fp, "Cache-control: private\n");
fputs($fp, "Pragma: no-cache\n");
fputs($fp, "Connection: close\n\n");

$text = '';
while (!feof($fp)){

  $text .= fgets($fp, 1024);
}

fclose($fp);

if(!empty($text)){ 
 
  $item = explode("<item>", $text);
  $count = count($item);
.
.
.
.
.
이하 상동
바쁘신데 살펴주셔서 감사합니다.
제 계정이 여러가지로 특이한 환경인가 봅니다.
알려주신대로 할 경우,
불여우에서는 일부 문자가 깨어지지만 바로 읽어서 처리는 됩니다.
그런데 이상하게 IE에서는 빈 페이지가 출력됩니다.
http://gnusr.com/Ysample/Yallblog_rss_utf_t.php

개인 용도이고 급하거나 하지 않습니다.
나중에 시간되실때 추가 검토해주시면 고맙겠습니다.
네 확인해 보았습니다

그 페이지를 소스 보기 하시면

문자가 깨지긴 하지만 내용을 제대로 가져왔음을 알수 있을것입니다.

utf8로 사용하실경우

해당 파일을 editplus에서 utf-8로 저장하세요.

아마 그러면 잘 되지 않을 까 싶네요.

반대로 euc-kr로 사용할경우에는

ansi로 저장을 하고

$text .= fgets($fp, 1024);

줄 다음에 iconv를 사용하여 utf-8을 euc-kr로 변환해서 사용하면 됩니다.
대단히 감사합니다.
저장에서 인코딩 선택에 문제가 있었습니다.
사소한 문제로 번거롭게 해드려 죄송합니다. 이제 모두 잘됩니다.
널리 응용할수 있는 멋진 코드를 공개해주셔서 거듭 감사합니다.
전체 5,352
개발자팁 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT