PHP로 RSS/Atom 피드 구문 분석
Magpie RSS를 사용하여 RSS 또는 Atom 피드를 구문 분석할 때 처리할 수 있는 대체 옵션을 고려하는 것이 중요합니다. 잘 구성된 피드. 그러한 옵션 중 하나가 SimpleXML입니다.
PHP에 내장된 SimpleXML은 XML 문서를 구문 분석하기 위한 사용자 친화적인 구조를 제공합니다. XML 오류를 감지하고 문제가 발생하면 경고합니다. 이러한 오류를 해결하려면 HTML Tidy를 사용하여 소스를 정리하는 것을 고려할 수 있습니다.
SimpleXML을 사용하여 RSS 피드를 구문 분석하는 기본 클래스는 다음과 같습니다.
class BlogPost { public $date; public $ts; public $link; public $title; public $text; } class BlogFeed { public $posts = []; public 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; $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); $max_len = 100; if (strlen($summary) > $max_len) $summary = substr($summary, 0, $max_len) . '...'; return $summary; } }
SimpleXML을 활용하고 XML 오류를 처리하면 PHP를 사용하여 RSS와 Atom 피드를 모두 효과적으로 구문 분석할 수 있습니다.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3