[php] PHP로 RSS / Atom 피드를 파싱하는 가장 좋은 방법 [닫기]

나는 현재 사용하고 있습니다 Magpie RSS를 있지만 RSS 또는 Atom 피드가 제대로 구성되지 않으면 때때로 넘어집니다. PHP로 RSS 및 Atom 피드를 구문 분석하는 다른 옵션이 있습니까?



답변

다른 옵션은 다음과 같습니다.


답변

필자는 항상 PHP내장 된 SimpleXML 함수를 사용 하여 XML 문서를 구문 분석했습니다. 직관적 인 구조를 가진 몇 가지 일반적인 파서 중 하나이므로 RSS 피드와 같은 특정 클래스에 대한 의미있는 클래스를 매우 쉽게 만들 수 있습니다. 또한 XML 경고 및 오류를 감지하고 HTML dydy (ceejayoz가 언급했듯이)를 통해 소스를 실행하여 정리하고 다시 시도 할 수 있습니다.

SimpleXML을 사용하여 매우 거칠고 간단한 클래스를 고려하십시오.

class BlogPost
{
    var $date;
    var $ts;
    var $link;

    var $title;
    var $text;
}

class BlogFeed
{
    var $posts = array();

    function __construct($file_or_url)
    {
        $file_or_url = $this->resolveFile($file_or_url);
        if (!($x = simplexml_load_file($file_or_url)))
            return;

        foreach ($x->channel->item as $item)
        {
            $post = new BlogPost();
            $post->date  = (string) $item->pubDate;
            $post->ts    = strtotime($item->pubDate);
            $post->link  = (string) $item->link;
            $post->title = (string) $item->title;
            $post->text  = (string) $item->description;

            // Create summary as a shortened body and remove images, 
            // extraneous line breaks, etc.
            $post->summary = $this->summarizeText($post->text);

            $this->posts[] = $post;
        }
    }

    private function resolveFile($file_or_url) {
        if (!preg_match('|^https?:|', $file_or_url))
            $feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $file_or_url;
        else
            $feed_uri = $file_or_url;

        return $feed_uri;
    }

    private function summarizeText($summary) {
        $summary = strip_tags($summary);

        // Truncate summary line to 100 characters
        $max_len = 100;
        if (strlen($summary) > $max_len)
            $summary = substr($summary, 0, $max_len) . '...';

        return $summary;
    }
}


답변

4 줄로 rss를 배열로 가져옵니다.

$feed = implode(file('http://yourdomains.com/feed.rss'));
$xml = simplexml_load_string($feed);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

보다 복잡한 솔루션

$feed = new DOMDocument();
 $feed->load('file.rss');
 $json = array();
 $json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
 $json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
 $json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
 $items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');

 $json['item'] = array();
 $i = 0;

 foreach($items as $key => $item) {
 $title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
 $description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
 $pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
 $guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;

 $json['item'][$key]['title'] = $title;
 $json['item'][$key]['description'] = $description;
 $json['item'][$key]['pubdate'] = $pubDate;
 $json['item'][$key]['guid'] = $guid;
 }

echo json_encode($json);


답변

RSS를 구문 분석하는 간단한 스크립트를 소개하고 싶습니다.

$i = 0; // counter
$url = "http://www.banki.ru/xml/news.rss"; // url to parse
$rss = simplexml_load_file($url); // XML parser

// RSS items loop

print '<h2><img style="vertical-align: middle;" src="'.$rss->channel->image->url.'" /> '.$rss->channel->title.'</h2>'; // channel title + img with src

foreach($rss->channel->item as $item) {
if ($i < 10) { // parse only 10 items
    print '<a href="'.$item->link.'">'.$item->title.'</a><br />';
}

$i++;
}


답변

피드의 형식이 잘못된 XML 인 경우 예외없이 거부해야합니다. 피드 제작자 에게 bozo 를 호출 할 수 있습니다.

그렇지 않으면 HTML이 끝나는 것을 망칠 수 있습니다.


답변

HTML Tidy 라이브러리는 잘못된 XML 파일을 수정할 수 있습니다. 피드를 파서에 전달하기 전에 피드를 실행하면 도움이 될 수 있습니다.


답변

SimplePie 를 사용 하여 Google 리더 피드를 구문 분석하고 제대로 작동하며 적절한 기능 세트가 있습니다.

물론, 잘 구성되지 않은 RSS / Atom 피드로 테스트하지 않았으므로 어떻게 대처하는지 모릅니다 .Google의 표준을 준수한다고 가정합니다. 🙂