I'm trying to set up a live feed from a blog, but the contents are not displays. Any ideas? The blog is based in WP, I've set a contents curl below to a php file. The php file contains another curl to the physical blog feed.
<?php
try{
// Get RSS feed
$blog_feed = #file_get_contents_curl('http://www.coordsport.com/csblogfeed.php');
if ($blog_feed){
// Convert to traversable XML object
$blog_posts = new SimpleXMLElement($blog_feed);
// Set limits and counter
$list_count = 5;
$current_item = 0;
// Loop through each feed item
foreach ($blog_posts->channel->item as $blog_post)
{
// Increment counter and check count
if (++$current_item > $list_count) break;
// Force data type for description
$post_description = (string)$blog_post->description;
$desc_xml = new SimpleXMLElement('<div>' . $post_description . '</div>');
// Reset thumbnail
$thumbnail_src = '';
if (#$desc_xml->img[0])
{
$thumbnail_src = (string) $desc_xml->img[0]->attributes()->src;
}
}
else
{
echo 'Error Loading Feed';
}
}
catch(Exception $e)
{
echo 'Error Loading Feed.<br /><br /><div style="font-size:75%;color:#ccc;">' . htmlspecialchars($e) . '</div>';
}
?>
The file_get_contents_curl csblogfeed.php contains, the blog is working fine and displays correctly in the below URL.
<?php
echo file_get_contents('http://www.coordsport.com/blog/feed/');
?>
Related
I am adding an RSS feed to my website. I created the RSS.xml index file and next I want to display its contents in a nicely formatted way in a webpage.
Using PHP, I can do this:
$index = file_get_contents ($path . 'RSS.xml');
echo $index;
But all that does is dump the contents as a long stream of text with the tags removed.
I know that treating RSS.xml as a link, like this:
<a href="../blogs/RSS.xml">
<img src="../blogs/feed-icon-16.gif">Blog Index
</a>
causes my browser to parse and display it in a reasonable way when the user clicks on the link. However I want to embed it directly in the web page and not make the user go through another click.
What is the proper way to do what I want?
Use the following code:
include_once('Simple/autoloader.php');
$feed = new SimplePie();
$feed->set_feed_url($url);
$feed->enable_cache(false);
$feed->set_output_encoding('utf-8');
$feed->init();
$i=0;
$items = $feed->get_items();
foreach ($items as $item) {
$i++;
/*You are getting title,description,date of your rss by the following code*/
$title = $item->get_title();
$url = $item->get_permalink();
$desc = $item->get_description();
$date = $item->get_date();
}
Download the Simple folder data from : https://github.com/jewelhuq/Online-News-Grabber/tree/master/worldnews/Simple
Hope it will work for you. There $url mean your rss feed url. If you works then response.
Turns out, it's simple by using the PHP xml parer function:
$xml = simplexml_load_file ($path . 'RSS.xml');
$channel = $xml->channel;
$channel_title = $channel->title;
$channel_description = $channel->description;
echo "<h1>$channel_title</h1>";
echo "<h2>$channel_description</h2>";
foreach ($channel->item as $item)
{
$title = $item->title;
$link = $item->link;
$descr = $item->description;
echo "<h3><a href='$link'>$title</a></h3>";
echo "<p>$descr</p>";
}
I'm working on a project and it's something new for me. I'll need to fetch rss content from websites, and display Descripion, Title and Images (Thumbnails). Right now i've noticed that some feeds show thumbnails as Enclosure tag and some others dont. right now i have the code for both, but i need to understand how i can create a conditional like:
If the rss returns enclosure image { Do something }
Else { get the common thumb }
Here follow the code that grab the images:
ENCLOSURE TAG IMAGE:
if ($enclosure = $block->get_enclosure())
{
echo "<img src=\"" . $enclosure->get_link() . "\">";
}
NOT ENCLOSURE:
if ($enclosure = $block->get_enclosure())
{
echo '<img src="'.$enclosure->get_thumbnail().'" title="'.$block->get_title().'" width="200" height="200">';
}
=================================================================================================
PS: If we look at both codes they're almost the same, the difference are get_thumbnail and get_link.
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Thanks everyone in advance!
EDITED
Here is the full code i have right now:
include_once(ABSPATH . WPINC . '/feed.php');
if(function_exists('fetch_feed')) {
$feed = fetch_feed('http://feeds.bbci.co.uk/news/world/africa/rss.xml'); // this is the external website's RSS feed URL
if (!is_wp_error($feed)) : $feed->init();
$feed->set_output_encoding('UTF-8'); // this is the encoding parameter, and can be left unchanged in almost every case
$feed->handle_content_type(); // this double-checks the encoding type
$feed->set_cache_duration(21600); // 21,600 seconds is six hours
$feed->handle_content_type();
$limit = $feed->get_item_quantity(18); // fetches the 18 most recent RSS feed stories
$items = $feed->get_items(0, $limit); // this sets the limit and array for parsing the feed
endif;
}
$blocks = array_slice($items, 0, 3); // Items zero through six will be displayed here
foreach ($blocks as $block) {
//echo $block->get_date("m d Y");
echo '<div class="single">';
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
echo '<div class="description">';
echo '<h3>'. $block->get_title() .'</h3>';
echo '<p>'.$block->get_description().'</p>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
}
And here are the XML pieces with 2 different tags for images:
Using Thumbnails: view-source:http://feeds.bbci.co.uk/news/world/africa/rss.xml
Using Enclosure: http://feeds.news24.com/articles/news24/SouthAfrica/rss
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Sure there is. You've not said in your question what blocks you so I have to assume the reason, but I can imagine multiple.
Is the reason a decisions with more than two alternations?
You handle the scenario of a feed item having no image or an image already:
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
With your current scenario there is only one additional alternation which makes it three: if the enclosure is a thumbnail and not a link:
No image (no enclosure)
Image from link (enclosure with link)
Image from thumbnail (enclosure with thumbnail)
And you then don't know how to create a decision of that. This is what basically else-if is for:
if (!$enclosure = $block->get_enclosure())
{
echo "no enclosure: ", "-/-", "\n";
} elseif ($enclosure->get_link()) {
echo "enclosure link: ", $enclosure->get_link(), "\n";
} elseif ($enclosure->get_thumbnail()) {
echo "enclosure thumbnail: ", $enclosure->get_thumbnail(), "\n";
}
This is basically then doing the output based on that. However if you assign the image URL to a variable, you can decide on the output later on:
$image = NULL;
if (!$enclosure = $block->get_enclosure())
{
// nothing to do
} elseif ($enclosure->get_link()) {
$image = $enclosure->get_link();
} elseif ($enclosure->get_thumbnail()) {
$image = $enclosure->get_thumbnail();
}
if (isset($image)) {
// display image
}
And if you then move this more or less complex decision into a function of it's own, it will become even better to read:
$image = feed_item_get_image($block);
if (isset($image)) {
// display image
}
This works quite well until the decision becomes even more complex, but this would go out of scope for an answer on Stackoverflow.
i'm trying to display some custom facebook feeds on my website from a facebook fan page.
This is a summary sample of the php I used, and it works fine.
[...html code...]
// include the facebook sdk
require_once('resources/facebook-php-sdk-master/src/facebook.php');
// connect to app
$config = array();
$config['appId'] = 'MY_APP_ID';
$config['secret'] = 'MY_SECRET_CODE';
$config['fileUpload'] = false; // optional
// instantiate
$facebook = new Facebook($config);
// set page id
$pageid = "MY_PAGE_ID";
// access to the graph, starting with the feed
$pagefeed = $facebook->api("/" . $pageid . "/feed");
[...html code...]
$i = 0;
foreach($pagefeed['data'] as $post) {
// check if post type is a photo and catch the various part of the graph
if ($post['type'] == 'photo') {
//grab the thumbnail url in the graph
$picture_url = $post['picture'];
//get true sized photo by manipulating its url
$picture_url_big = str_replace("s130x130/","", $picture_url);
echo "<p><img class=\"img-icon\" src=\"" . $post['icon'] . "\"></p>";
echo "<h2 class=\"data-post\">" . date("j-n-Y", (strtotime($post['created_time']))) . "</h2>";
//displaying the photo
echo "<div class=\"img-thumb\"><img src=\"" . $picture_url_big . "\"></div>";
echo "<p class=\"manda-a-capo\"></p>";
if (empty($post['story']) === false) {
echo "<p>" . $post['story'] . "</p>";
} elseif (empty($post['message']) === false) {
echo "<p>" . $post['message'] . "</p>";
}
echo "<p><u><b>Vedi foto</b></u></p>";
echo "<p class=\"manda-a-capo\"></p>";
if ($post['shares']['count'] != "") {
echo "<p class=\"manda-a-capo share-num\">" . $post['shares']['count'] . " condivisioni.</p>";
}
}
$i++;
}
[...other code...]
The facebook graph contains only the thumb url of the photos, that is 130x130px. I discovered that some thumbs have an "/s130x130/" parameter in the url and, if you delete this parameter, you get the photo in its actual size.
So this explains this part of code (as above):
//grab the thumbnail url in the graph
$picture_url = $post['picture'];
//get true sized photo by manipulating its url
$picture_url_big = str_replace("s130x130/","", $picture_url);
//then displaying the photo
echo "<div class=\"img-thumb\"><img src=\"" . $picture_url_big . "\"></div>";
Unfortunately I noticed that not all photos from the page have this parameter and some of them have even a different url structure.
So the final result is that I can reach only few photos in their actual size, others remain a broken link.
Is there a way to manipulate the url to get all the photos in their own actual size?
Any advices?
Thanks.
P.S.
Here's the php to view the fb graph:
<?php
echo "<pre>";
print_r($pagefeed);
echo "</pre>";
?>
I found a temporary solution. In order to display the missing links I've added a php function that checks if the image url exist or not.
function checkRemoteFile($picture_url_big)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$picture_url_big);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
And a control just above the "echo"
if (checkRemoteFile($picture_url_big)) {
//echo "image exist ";
$check = true;
$picture_url_big;
} else {
//echo "image does not exist ";
$check = false;
$picture_url_big = $picture_url;
}
Im getting the contents of an xml feed and printing the titles on my web page with php:
$url = 'http://site.com/feed';
$xml = simplexml_load_file($url);
foreach($xml->ART as $ART) {
echo $ART->TITLE;
}
I want to be able to set a backup, so if the first xml isn't found a different one is loaded instead.
I tried the following code but it doesn't work. If the feed isnt found the page shows 'XML Parsing Error:' which i guess isnt the same as nothing.
if ($url != '') {
$xml = simplexml_load_file($url);
} else {
//Here I would load a different xml file.
}
What should I do? Should I write conditional php to check if the first url contains a TITLE, and if not load the 2nd url?
Thanks
UPDATE
This messed up my whole page:
$first_url = 'http://site.com/feed1';
$second_url = 'http://site.com/feed2';
// if URL wrappers is enabled
if (is_url($first_url))
{
// parse first url
$xml = simplexml_load_file($first_url);
}
else
{
// parse second url
$xml = simplexml_load_file($second_url);
}
foreach($xml->ART as $ART) {
echo $ART->TITLE;
}
See simplexml_load_file
Returns an object of class SimpleXMLElement with properties containing the data held within the XML document. On errors, it will return FALSE.
Example from php.net
<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.
if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');
print_r($xml);
} else {
exit('Failed to open test.xml.');
}
?>
EDIT: you can do
$url = 'http://site.com/feed';
if( $xml = simplexml_load_file($url) ) {
foreach($xml->ART as $ART) {
echo $ART->TITLE;
}
} else {
//parsing new url
}
function parse_xml($url)
{
// your code
}
try
{
parse_xml($first_url);
}
catch (Exception $e)
{
parse_xml($second_url);
}
Alternatively, you can do a check if the URL return XML before proceed to parsing :-
// if URL wrappers is enabled
if (is_url($first_url))
{
// parse first url
$xml = simplexml_load_file($first_url);
}
else
{
// parse second url
$xml = simplexml_load_file($second_url);
}
Think ive got it working with:
$url = 'site.com/feed1';
$xml = simplexml_load_file($url);
if ($xml == null) {
$url = 'site.com/feed2';
$xml = simplexml_load_file($url);
}
foreach($xml->ART as $ART) {
echo $ART->TITLE;
}
Hi I have been having problems with the google weather api having errors Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 2: parser error ....
I tried to use the script of the main author(thinking it was my edited script) but still I am having this errors I tried 2
//komunitasweb.com/2009/09/showing-the-weather-with-php-and-google-weather-api/
and
//tips4php.net/2010/07/local-weather-with-php-and-google-weather/
The weird part is sometimes it fixes itself then goes back again to the error I have been using it for months now without any problem, this just happened yesterday. Also the demo page of the authors are working but I have the same exact code any help please.
this is my site http://j2sdesign.com/weather/widgetlive1.php
#Mike I added your code
<?
$xml = file_get_contents('http://www.google.com/ig/api?weather=jakarta'); if (! simplexml_load_string($xml)) { file_put_contents('malformed.xml', $xml); }
$xml = simplexml_load_file('http://www.google.com/ig/api?weather=jakarta');
$information = $xml->xpath("/xml_api_reply/weather/forecast_information");
$current = $xml->xpath("/xml_api_reply/weather/current_conditions");
$forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions");
?>
and made a list of the error but I can't seem to see the error cause it's been fixing itself then after sometime goes back again to the error
here is the content of the file
<?php include_once('simple_html_dom.php'); // create doctype $dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes //header("Content-Type: text/plain");
// create root element
$xmlProducts = $dom->createElement("products");
$dom->appendChild($xmlProducts);
$pages = array( 'http://myshop.com/small_houses.html', 'http://myshop.com/medium_houses.html', 'http://myshop.com/large_houses.html' ) foreach($pages as $page) { $product = array(); $source = file_get_html($page); foreach($source->find('img') as $src) { if (strpos($src->src,"http://myshop.com") === false) { $product['image'] = "http://myshop.com/$src->src"; } } foreach($source->find('p[class*=imAlign_left]') as $description) { $product['description'] = $description->innertext; } foreach($source->find('span[class*=fc3]') as $title) { $product['title'] = $title->innertext; } //debug perposes! echo "Current Page: " . $page . "\n"; print_r($product); echo "\n\n\n"; //Clear seperator } ?>
When simplexml_load_string() fails you need to store the data you're trying to load somewhere for review. Examining the data is the first step to diagnose what it causing the error.
$xml = file_get_contents('http://example.com/file.xml');
if (!simplexml_load_string($xml)) {
file_put_contents('malformed.xml', $xml);
}