编程语言
首页 > 编程语言> > PHP简单HTML DOM解析器-RSS中的链接元素

PHP简单HTML DOM解析器-RSS中的链接元素

作者:互联网

我刚刚开始使用PHP简单HTML DOM解析器(http://simplehtmldom.sourceforge.net/),但在解析XML时遇到了一些问题.

我可以完美地解析HTML文档中的所有链接,但是无法解析RSS feed(XML格式)中的链接.例如,我想解析来自http://www.bing.com/search?q=ipod&count=50&first=0&format=rss的所有链接,因此我使用以下代码:

$content = file_get_html('http://www.bing.com/search?q=ipod&count=50&first=0&format=rss');

foreach($content->find('item') as $entry)
{
$item['title']     = $entry->find('title', 0)->plaintext;
$item['description']    = $entry->find('description', 0)->plaintext;
$item['link'] = $entry->find('link', 0)->plaintext;
$parsed_results_array[] = $item;
}

print_r($parsed_results_array);

该脚本分析标题和描述,但链接元素为空.有任何想法吗?我的猜测是“链接”是保留字或其他东西,那么如何使解析器正常工作?

解决方法:

我建议您使用正确的工具来完成这项工作.使用SimpleXML:另外,它是内置的:)

$xml = simplexml_load_file('http://www.bing.com/search?q=ipod&count=50&first=0&format=rss');
$parsed_results_array = array();
foreach($xml as $entry) {
    foreach($entry->item as $item) {
        // $parsed_results_array[] = json_decode(json_encode($item), true);
        $items['title'] = (string) $item->title;
        $items['description'] = (string) $item->description;
        $items['link'] = (string) $item->link;
        $parsed_results_array[] = $items;
    }
}

echo '<pre>';
print_r($parsed_results_array);

应该产生如下内容:

Array
(
    [0] => Array
        (
            [title] => Apple - iPod
            [description] => Learn about iPod, Apple TV, and more. Download iTunes for free and purchase iTunes Gift Cards. Check out the most popular TV shows, movies, and music.
            [link] => http://www.apple.com/ipod/
        )

    [1] => Array
        (
            [title] => iPod - Wikipedia, the free encyclopedia
            [description] => The iPod is a line of portable media players designed and marketed by Apple Inc. The first line was released on October 23, 2001, about 8½ months after ...
            [link] => http://en.wikipedia.org/wiki/IPod
        )

标签:simplexml,xml,php
来源: https://codeday.me/bug/20191029/1959096.html