Hello i have wordpress website i have around 100 post in it and i daily update them
i want to display latest 3 post on remote website is this possible with any rss feed parsing or any other method.I tried with below code but it shows failed
<?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;
?>
I tried even with
$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);
but it shows error as well
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
Wordpress provide function to fetch remote data. So you can use that.see below code
$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);
Your code works.
<?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
(...)
Your URL is not working because:
$ curl -D- http://project.demotestserver.com/brand_new/feed
HTTP/1.1 301 Moved Permanently
(...)
Location: http://project.demotestserver.com/brand_new/feed/
You can check the headers with PHP-curl too, check the docs.