用DOM解析PHP中的RSS源 [英] Parsing an RSS feed in PHP with DOM

查看:127
本文介绍了用DOM解析PHP中的RSS源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从RSS提要中创建一组项目。我试图通过回应第一个项目的标题来测试它是否正常工作。我一直没有成功到目前为止...我真的很感激任何建议!

I'm trying to create an array of items from an RSS feed. I'm trying to test if it's working by echoing the title of the first item. I've been unsuccessful so far...I'd really appreciate any advice!

我有两个文件,一个'index.php'和'test.php '。

I have two files, an 'index.php' and a 'test.php'.

<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type= "text/css" href = "style.css">
</head>

<body>

<h1>TEST SLIDER</h1>

<p>First Title:<br>
<?php

    include 'test.php';
    $NPR_url = 'http://www.npr.org/rss/rss.php?id=1001';
    $NPR = GetFeed($NPR_url);
    echo $NPR[0]['title'];

?>
</p>

</body>
</html>

和'test.php'

and 'test.php'

<?php

    function GetFeed($url){
        $feed = new DOMDocument;
        $feed->load($url);
        $feed_array = array();

        foreach($feed->getElementsByTagName('item') as $story){
            $story_array = array (
                                  'title' => $story->getElementsByTagName('title')->item(0)->nodeValue,
                                  'desc' => $story->getElementsByTagName('description')->item(0)->nodeValue,
                                  'link' => $story->getElementsByTagName('link')->item(0)->nodeValue,
                                  'date' => $story->getElementsByTagName('pubDate')->item(0)->nodeValue
            );

            array_push($feed_array, $story_array);
        }

        return $feed_array;
    }


?>


推荐答案

解析后,DOMDocument无法获取channel对象。这是使用simpleXML的GetFeed()函数:

DOMDocument could not get the 'channel' object after parsing. Here's the GetFeed() function using simpleXML:

test.php

    <?php
    function GetFeed($url){
        $feed = simplexml_load_file($url);
        $feed_array = array();
        foreach($feed->channel->item as $story){
            $story_array = array (
                                  'title' => $story->title,
                                  'desc' => $story->description,
                                  'link' => $story->link,
                                  'date' => $story->date
            );

            array_push($feed_array, $story_array);
        }

        return $feed_array;
    }
    ?>

希望有帮助。您的index.php将保持不变。

Hope it helps. Your index.php will remain same.

这篇关于用DOM解析PHP中的RSS源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆