【问题标题】:Parsing Reddit RSS feed - PHP解析 Reddit RSS 提要 - PHP
【发布时间】:2016-09-20 07:13:04
【问题描述】:

我正在尝试获取 rss 提要的标题和链接 -

https://www.reddit.com/r/gif.rss 

(reddit 提要)

xml=simplexml_load_file("https://www.reddit.com/r/gif.rss") or die("Error: Cannot create object");

foreach ($xml->entry->content as $x) {
$title = $x->title;
$string = $x->link;
echo $title;
echo "<br>";
echo $string;
}

我无法显示标题或链接。

【问题讨论】:

  • 我没有看到任何 echo 语句
  • 我尝试回显标题和字符串 - 没有任何反应
  • $x 是一个字符串对象,你可以回显它。您必须从 $x 解析 html。

标签: php xml


【解决方案1】:

只需调整路径表达式。 &lt;content&gt; 节点不包含 &lt;title&gt;&lt;link&gt; 子节点,尽管它们的内容包含在内容的文本值中。相反,您需要的节点是兄弟节点,因此请删除循环路径中的 &lt;content&gt;

$xml = simplexml_load_file("https://www.reddit.com/r/gif.rss") 
                              or die("Error: Cannot create object");
foreach ($xml->entry as $x) {
    $title = $x->title;
    $string = $x->link['href'];
    echo $title;
    echo "<br>";
    echo $string;
}

// This guy loves his job
// <br>
// https://www.reddit.com/r/gif/comments/53i3jc/this_guy_loves_his_job/
// Letron BMW E92 Transformer
// <br>
// https://www.reddit.com/r/gif/comments/53i13r/letron_bmw_e92_transformer/
// MRW "you're cute when you're angry"
// <br>
// https://www.reddit.com/r/gif/comments/53ihpf /mrw_youre_cute_when_youre_angry/
// Pussy Pass Denied
// <br>
// https://www.reddit.com/r/gif/comments/53hm3w/pussy_pass_denied/
// My favorite reverse gif so far
// <br>
// https://www.reddit.com/r/gif/comments/53ihwr/my_favorite_reverse_gif_so_far/
// Oh hooman, you will hug me. --Dog
// <br>
// https://www.reddit.com/r/gif/comments/53cbcq/oh_hooman_you_will_hug_me_dog/
...

【讨论】:

    【解决方案2】:

    整理一下:

    $xml=simplexml_load_file("https://www.reddit.com/r/gif.rss") or die("Error: Cannot create object");
    
    function extractString($string, $start, $end) {
        $string = " ".$string;
        $ini = strpos($string, $start);
        if ($ini == 0) return "";
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        return substr($string, $ini, $len);
    }
    
    
    foreach ($xml->entry as $x) {
    $string = $x->content;
    
    $url =  extractString($string, '<span><a href="', '">[link]</a></span>');
    $title = extractString($string, 'alt="', '" title');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 2014-08-26
      相关资源
      最近更新 更多