Loading RSS file with DOMDocument

僤鯓⒐⒋嵵緔 提交于 2020-01-16 18:40:14

问题


I'm having an issue with my PHP assignment for school. I have to create a PHP script that reads an XML file with bunch of URLs to different RSS feeds. I'm using DOMDocument to retrieve an URL from this XML file and load a new DOM with the RSS feed. I assign the "url" node value to $url and then create a new DOM object for the RSS feed using $url.

$url = $student->getElementsByTagName("url");
$url = $url->item(0)->nodeValue;


$rss = new DOMDocument();
$rss->load($url);

The RSS file will not load when I use the code above. I even echoed $url to make sure that it has a link assigned to it. However, if I put the actual url into the load(), it works just fine. Why isn't $url working in load()?


回答1:


You can use simplexml_load_file in this case, but remember, all these operations are costly (time limit, memory etc..).

$rssStack = array();
$xml = simplexml_load_file("http://people.rit.edu/cns3946/539/project2/rss_class.xml");
foreach ($xml->student as $student) {
    // need sanitize $url
    $url = trim((string) $student->url);
    // suppress errors, cos some urls return "404 Not Found"
    $rss =@ simplexml_load_file($url);
    $rssStack[] = $rss;
    // also can use 
    // $rss = new DOMDocument();
    // $rss->load($url);
    // $rssStack[] = $rss;
}
print_r($rssStack);

UPDATE

$rssStack = array();
$xml = new DOMDocument();
$xml->load("http://people.rit.edu/cns3946/539/project2/rss_class.xml");
foreach ($xml->getElementsByTagName("url") as $url) {
    // you need to sanitize url
    $url = trim($url->nodeValue);
    $rss = new DOMDocument();
    $rss->load($url);
    $rssStack[] = $rss;
    // break;
}
print_r($rssStack);


来源:https://stackoverflow.com/questions/14659162/loading-rss-file-with-domdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!