在远程php网站上显示wordpress帖子

时间:2014-03-07 05:53:37

标签: php wordpress parsing rss

你好我有wordpress网站我有大约100个帖子,我每天更新它们

我想在远程网站上显示最新的3篇文章这可能与任何rss feed解析或任何其他方法。我试过下面的代码,但它显示失败

<?php 
        $feedUrl = 'http://testserver.com/brand_new/feed';
        $rawFeed = file_get_contents($feedUrl);

        print_r($rawFeed);
        exit;

         $anobii = new SimpleXmlElement($rawFeed);

        foreach ($anobii->channel->item as $anobiiinfo):
            $title=$anobiiinfo->title;
            $desc=$anobiiinfo->description;       
            echo "<span> ",$title,"</span> <br/> <span> ",$desc,"</span>";
        endforeach;
    ?>

我甚至试过

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://wallpapers.celeborama.net/feed/');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);

$xml = new SimpleXMLElement($data);

但它也显示错误

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in G:\xampp\htdocs\wpfeed.php:11 Stack trace: #0 G:\xampp\htdocs\wpfeed.php(11): SimpleXMLElement->__construct('') #1 {main} thrown in G:\xampp\htdocs\wpfeed.php on line 11

2 个答案:

答案 0 :(得分:1)

Wordpress提供获取远程数据的功能。所以你可以使用它。见下面的代码

$feedUrl = 'http://project.demotestserver.com/brand_new/feed';
$data = wp_remote_retrieve_body(wp_remote_get($feedUrl, array( 'timeout' => 30000 ) ));
$dom = new DOMDocument;
$dom->loadXML($data);
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}
$xml = simplexml_import_dom($dom);
$posts = $xml->channel->item;
    $i=0;
    foreach($posts as $key => $post) {
       if($i>=3) continue;
        $title=$post->title;
        $i++;

    }

   print_r($title);

答案 1 :(得分:0)

您的代码有效。

<?php
$feed = 'http://rss.slashdot.org/Slashdot/slashdot';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $feed);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

//print_r($data);

$xml = new SimpleXMLElement($data);
foreach ($xml->channel->item as $i) {
    echo $i->title . PHP_EOL;
}
?>

-

$ php ~/tmp/so/php-feed/smple.xml.php 
Should Newsweek Have Outed Satoshi Nakamoto's Personal Details?
Stanford Team Tries For Better Wi-Fi In Crowded Buildings
Computer Program Allows the Blind To "See" With Sound
(...)

您的网址无效,因为:

$ curl -D-  http://project.demotestserver.com/brand_new/feed 
HTTP/1.1 301 Moved Permanently
(...)
Location: http://project.demotestserver.com/brand_new/feed/

您也可以使用PHP-curl检查标题,查看文档。