使用DOM解析PHP中的RSS提要

Gam*_*ean 2 php rss dom

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

我有两个文件,'index.php'和'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>
Run Code Online (Sandbox Code Playgroud)

和'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;
    }


?>
Run Code Online (Sandbox Code Playgroud)

anu*_*pam 5

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

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;
    }
    ?>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.您的index.php将保持不变.