반응형

그누보드를 수정하던 중 네이버 블로그에 글을 목록으로 구현하고 싶었다.

구글링을 통해 rss를 불러오는 소스를 구했다. 그런데 문제가 있었다. 

<?php
	$blog_rss= "https://rss.blog.naver.com/네이버ID.xml";
    //네이버 id 수정 필요
    $rss = simplexml_load_file($blog_rss);
    // xml을 로드해오는 함수
    
	$count = 1;
	foreach($rss->channel->item as $chan){
		if($count>5){
    	break;
        //5개만 불러오도록 설정했다.
    }?>
    
    <h2>
	<a href="<?php echo $chan->link ?>"> <?php echo $chan->title ?> </a>
	</h2>
    
    <?php echo $chan->description ?> <p>
    
    <?php $count++;}
     // 출처 : https://positiveline.tistory.com/entry/%EB%84%A4%EC%9D%B4%EB%B2%84-%EB%B8%94%EB%A1%9C%EA%B7%B8-%EC%B9%B4%ED%85%8C%EA%B3%A0%EB%A6%AC%EB%B3%84-RSS-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0PHP  를 기반으로 조금 수정했습니다. 
 ?>

나는 닷홈 무료 호스팅을 사용하고 있는데 아래의 소스에서 simplexml_load_file 함수를 사용하면 simplexml_load_file(): https:// wrapper is disabled in the server configuration by allow_url_fopen=0 in 오류가 발생했다. 즉 fopen 권한을 ON해줘야하는데 닷홈 무료호스팅은 php.ini 수정이 불가능했다.

 

구글링을 통해서 아래의 방법을 시도했다.

.htaccess 에  php_flag allow_url_fopen  코드 삽입.

ini_set('allow_url_fopen', 'On'); 코드를 php에 삽입.

그러나 모두 되지 않았다.

 

구글링을 하니 curl을 사용해 파싱해오라고 하였지만 파싱은됬는데 xml로 변환이 되지 않았다. 아무리 구글링해봐도 이를 해결할 한글 문서가 없어 결국 이 글을 작성했다.

 

<?php
	$blog_rss= "https://rss.blog.naver.com/네이버ID.xml";
    //네이버 id 수정 필요 rss 2.0기준.
	$rss = curl_get_file_contents($blog_rss);
    //최하단의 함수를 통해 curl로 파싱을 해온다.
	$rss = simplexml_load_string($rss);
    //파싱해온 string을 xml로 변환해준다.
    
	$count = 1;
	foreach($rss->channel->item as $chan){
		if($count>5){
    	break;
        //5개만 불러오도록 설정했다.
        /*	위에 rss->channel->item as $chan관련 내용을 설명하자면.
        	네이버 블로그 xml에 <channel>안에 게시물이 전부 여러개의 <item> 요소로 나타난다.
            이 <item>요소안에 <title>요소(제목), <link>요소(게시물 링크),<description>요소(내용)가 있다.
            반복문을 통해서 item요소를 순차적으로 $chan에 저장하고(그냥 chan이라 한거다 abc라 이름 지어도 상관없다.)
            echo $chan->title; 코드로 제목을 출력하는것이다.
        */
    }?>
    
    <h2>
	<a href="<?php echo $chan->link ?>"> <?php echo $chan->title ?> </a>
	</h2>
    
    <?php echo $chan->description ?> <p>
    <?php $count++;}
 ?>
 
 <?php
function curl_get_file_contents($URL)
{
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_URL, $URL);
    $contents = curl_exec($c);
    curl_close($c);

    if ($contents) return $contents;
    else return FALSE;
}
//구글링에서 구한 curl로 파싱하는 함수.
?>

 

$rss = curl_get_file_contents($blog_rss);
$rss = simplexml_load_string($rss);

결국 curl을 사용해 string형으로 파싱하고 simplexml_load_string함수를 통해  xml로 변환했다.

그리고 반복문을 돌며 출력했다. 끝!

반응형

+ Recent posts