Resend my activation email : Register : Log in 
BCF: Bike Chat Forums


Display RSS feed on my PHP page

Reply to topic
Bike Chat Forums Index -> The Geek Zone
View previous topic : View next topic  
Author Message

andrew
Mister Road Rage



Joined: 03 Feb 2002
Karma :

PostPosted: 12:14 - 12 Jan 2009    Post subject: Display RSS feed on my PHP page Reply with quote

Hi, i'm trying to display an rss feed on a php page of mine and needed some help.

Somebody gave me this script:

Code:

<?php 
// rss page for Testing - 
$feed_url = "http://rss.feedsportal.com/c/669/f/9809/index.rss";

$xml = simplexml_load_file($feed_url);

// How many items to display
$count = 5;

// How many characters from each item
// 0 (zero) will show them all.
$char = 0;

foreach ($xml->channel->item as $item) {
if($char == 0){
$newstring = $item->description;
}
else{
$newstring = substr($item->description, 0, $char);
}
if($count > 0){
//in case they have non-closed italics or bold, etc ...
echo"</i></b></u></a>\n";
echo"
<div style='font-family:arial; font-size:.8em;'> 
<b>{$item->title}</b><br />
$newstring ... <a href='{$item->guid}'>read more</a>
<br /><br />
</div>
"; 
}
$count--;
}


?>


Now this works, it's just i need to know how to strip out the images. Does anybody here have any ideas?

Cheers
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

Kickstart
The Oracle



Joined: 04 Feb 2002
Karma :

PostPosted: 12:34 - 12 Jan 2009    Post subject: Reply with quote

Hi

Quick try. This is pretty crude and there are probably better ways of doing it from someone who properly knows their way round regular expressions.

Code:

<?php 
// rss page for Testing - 
$feed_url = "http://rss.feedsportal.com/c/669/f/9809/index.rss";

$xml = simplexml_load_file($feed_url);

// How many items to display
$count = 5;

// How many characters from each item
// 0 (zero) will show them all.
$char = 0;

foreach ($xml->channel->item as $item)
{
   if($char == 0)
   {
      $newstring = $item->description;
   }
   else
   {
      $newstring = substr($item->description, 0, $char);
   }
   
   $newstringarray = preg_split("/(<.*?>)/",$text,-1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
   
   $newstring2 = "";
   $inimage = false;
   foreach ($newstringarray as $newstringitem)
   {
      if (inimage)
      {
         if (substr(strtolower($newstringitem),0,5) == "</img")
         {
            $inimage = false;
         }
      }
      else
      {
         if (substr(strtolower($newstringitem),0,4) == "<img")
         {
            $inimage = true;
         }
         else
         {
            $newstring2 .= $newstringitem;
         }
      }
   }
   
   if($count > 0)
   {
      //in case they have non-closed italics or bold, etc ...
      echo"</i></b></u></a>\n";
      echo"
      <div style='font-family:arial; font-size:.8em;'> 
      <b>{$item->title}</b><br />
      $newstring2 ... <a href='{$item->guid}'>read more</a>
      <br /><br />
      </div>
      "; 
   }
   $count--;
}


?>


One obvious bug is that leading spaces within an img tag which would probably work in the browser would be ignored in this script.

All the best

Keith
____________________
Traxpics, track day and racing photographs - Bimota Forum - Bike performance / thrust graphs for choosing gearing
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

andrew
Mister Road Rage



Joined: 03 Feb 2002
Karma :

PostPosted: 12:47 - 12 Jan 2009    Post subject: Reply with quote

Cheers keith, the only problem with that is in this feed it is totally stripping out the description that comes after the <img> tag, any ideas how this could be kept in and still controlled using the $char variable?
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

Kickstart
The Oracle



Joined: 04 Feb 2002
Karma :

PostPosted: 13:09 - 12 Jan 2009    Post subject: Reply with quote

Hi

Another try.

Code:

<?php 
// rss page for Testing - 
$feed_url = "http://rss.feedsportal.com/c/669/f/9809/index.rss";

$xml = simplexml_load_file($feed_url);

// How many items to display
$count = 15;

// How many characters from each item
// 0 (zero) will show them all.
$char = 0;

foreach ($xml->channel->item as $item)
{
   if($char == 0)
   {
      $newstring = $item->description;
   }
   else
   {
      $newstring = substr($item->description, 0, $char);
   }
   
   $newstringarray = preg_split("/(<.*?>)/",$newstring,-1,PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
   
   $newstring2 = "";
   foreach ($newstringarray as $newstringitem)
   {
      if (substr(strtolower($newstringitem),0,4) != "<img")
      {
         $newstring2 .= $newstringitem;
      }
   }
   
   if($count > 0)
   {
      //in case they have non-closed italics or bold, etc ...
      echo"</i></b></u></a>\n";
      echo"
      <div style='font-family:arial; font-size:.8em;'> 
      <b>{$item->title}</b><br />
      $newstring2 ... <a href='{$item->guid}'>read more</a>
      <br /><br />
      </div>
      "; 
   }
   $count--;
}


?>


All the best

Keith
____________________
Traxpics, track day and racing photographs - Bimota Forum - Bike performance / thrust graphs for choosing gearing
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

andrew
Mister Road Rage



Joined: 03 Feb 2002
Karma :

PostPosted: 13:18 - 12 Jan 2009    Post subject: Reply with quote

That's spot on, the only problem i have now is i've been told that it needs to cache the feeds so it doesn't request them everytime the page is loaded. Arrgghhh Very Happy
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

Kickstart
The Oracle



Joined: 04 Feb 2002
Karma :

PostPosted: 13:28 - 12 Jan 2009    Post subject: Reply with quote

Andrew wrote:
That's spot on, the only problem i have now is i've been told that it needs to cache the feeds so it doesn't request them everytime the page is loaded. Arrgghhh Very Happy


It is an off site cache. You store them on that web page Wink .

All the best

Keith
____________________
Traxpics, track day and racing photographs - Bimota Forum - Bike performance / thrust graphs for choosing gearing
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

andrew
Mister Road Rage



Joined: 03 Feb 2002
Karma :

PostPosted: 13:31 - 12 Jan 2009    Post subject: Reply with quote

The problem is, the page i'm putting them on gets quite a few hits, if i request the feeds too often they'll be blocked. Very Happy

How hard would it be to make that script request new rss items every 30 mins say and display what was grabbed in the last updated sorta thing?
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

Kickstart
The Oracle



Joined: 04 Feb 2002
Karma :

PostPosted: 13:35 - 12 Jan 2009    Post subject: Reply with quote

Hi

Read the RSS and store it in a text file somewhere on the server. Any further reads you check for the time / date of the saved file and refresh if old.

Or you do the above but store it on a database.

In either case you could store the processed version.

First is probably quicker and easier, but potentially less secure.

All the best

Keith
____________________
Traxpics, track day and racing photographs - Bimota Forum - Bike performance / thrust graphs for choosing gearing
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

andrew
Mister Road Rage



Joined: 03 Feb 2002
Karma :

PostPosted: 15:16 - 14 Jan 2009    Post subject: Reply with quote

Hi Keith, wondering if you could help me, i'm using a totally different bit of code now....

To parse the feed:
Code:

//FUNCTION TO PARSE RSS
  function parseRSS($url_tech) {

  //PARSE RSS FEED
  $feedeed = implode('', file($url_tech));
  $parser = xml_parser_create();
            xml_parse_into_struct($parser, $feedeed, $valueals, $index);
            xml_parser_free($parser);

  //CONSTRUCT ARRAY
  foreach($valueals as $keyey => $valueal){
    if($valueal['type'] != 'cdata') {
       $rss_item[$keyey] = $valueal; 
    }
  }

  $i = 0;
  foreach($rss_item as $key => $value){
    if($value['type'] == 'open') {
       $i++;
       $itemame[$i] = $value['tag'];
    } elseif($value['type'] == 'close') {
             $feed = $values[$i];
             $rss_item = $itemame[$i];
             $i--;

        if(count($values[$i])>1){
           $values[$i][$rss_item][] = $feed;
        } else { $values[$i][$rss_item] = $feed;
          }
      }   else { $values[$i][$value['tag']] = $value['value'];
          }
  }

   //RETURN ARRAY VALUES
        return $values[0];
   }


To draw it:
Code:


//PARSE THE RSS FEED INTO ARRAY
          $xml = parseRSS("http://rss.feedsportal.com/c/669/f/9809/index.rss");

          foreach($xml['RSS']['CHANNEL']['ITEM'] as $rss_item) {
                 $rss_title = $rss_item['TITLE'] ;
                  $rss_link = $rss_item['LINK'];

                // Limit FEED headline length
                $string_length = 200;

                if (strlen($rss_title) > $limit) {
                   $rss_title = substr($rss_title, 0, strrpos(substr($rss_title, 0, $string_length), ' '));
                }

          $tpl->setCurrentBlock("rss_tech");
            $tpl->setVariable(array(
               "rss_tech.title" => $rss_title,
              "rss_tech.link" => $rss_link,
          ));
          $tpl->parseCurrentBlock();
        }


This fits within the cache system on the site i'm working on but i have one question, how would i limit the results so it only displays the first 10 feeds, at the moment it's displaying the whole lot.

If you could help me with this it would be a big help.

Cheers
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

Kickstart
The Oracle



Joined: 04 Feb 2002
Karma :

PostPosted: 15:35 - 14 Jan 2009    Post subject: Reply with quote

Hi

This is using something I have never used in php, so not certain it will work.

Replace the "foreach" in your second code fragment with:-

Code:

        $count = 0;
        while ( list(,$rss_item) = each($xml['RSS']['CHANNEL']['ITEM']) AND $count++ < 5) {


You might have to reset the array before the while.

Or cruder

Code:

$count = 0;
foreach($xml['RSS']['CHANNEL']['ITEM'] as $rss_item) {
if ($count++ >= 5) break;


All the best

Keith
____________________
Traxpics, track day and racing photographs - Bimota Forum - Bike performance / thrust graphs for choosing gearing
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

andrew
Mister Road Rage



Joined: 03 Feb 2002
Karma :

PostPosted: 15:56 - 14 Jan 2009    Post subject: Reply with quote

Nice one. Thumbs Up Got it working using both methods, decided to carry on using the foreach.
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

andrew
Mister Road Rage



Joined: 03 Feb 2002
Karma :

PostPosted: 16:06 - 20 Jan 2009    Post subject: Reply with quote

Keith, do you know why this would be kicking out "Call to a member function on a non-object" errors?

Code:

//FUNCTION TO PARSE RSS
  function parseRSS($url_tech) {

  //PARSE RSS FEED
  $feedeed = implode('', file($url_tech));
  $parser = xml_parser_create();
            xml_parse_into_struct($parser, $feedeed, $valueals, $index);
            xml_parser_free($parser);

  //CONSTRUCT ARRAY
  foreach($valueals as $keyey => $valueal){
    if($valueal['type'] != 'cdata') {
       $rss_item[$keyey] = $valueal; 
    }
  }

  $i = 0;
  foreach($rss_item as $key => $value){
    if($value['type'] == 'open') {
       $i++;
       $itemame[$i] = $value['tag'];
    } elseif($value['type'] == 'close') {
             $feed = $values[$i];
             $rss_item = $itemame[$i];
             $i--;

        if(count($values[$i])>1){
           $values[$i][$rss_item][] = $feed;
        } else { $values[$i][$rss_item] = $feed;
          }
      }   else { $values[$i][$value['tag']] = $value['value'];
          }
  }

   //RETURN ARRAY VALUES
        return $values[0];
   }

  function draw_rss($pagecode) {
    global $CONFIG, $SITE, $CACHE_PAGES, $CHANNEL, $FORMAT, $SITE_BASEURL;

     $cache_ttl = 600;
    $cache_cat = 'rss_tech';
    $cache_key = $cache_cat . $SITE . $CHANNEL . $FORMAT;

    if (($html = get_cached_page($cache_key)) && $CACHE_PAGES) {
      dlog("Techradar box retrieved from cache");
    } else {
        dlog("Generating  box from scratch");

        $tpl = make_template('common_elements/rss.html');

          //PARSE THE RSS FEED INTO ARRAY
          $xml = parseRSS("feed");

        $count = 0;
          foreach($xml['RSS']['CHANNEL']['ITEM'] as $rss_item) {
               if ($count++ >= 10) break;
                 $rss_title = $rss_item['TITLE'] ;
                  $rss_link = $rss_item['LINK'];

                // Limit FEED headline length
                $string_length = 200;

                if (strlen($rss_title) > $limit) {
                   $rss_title = substr($rss_title, 0, strrpos(substr($rss_title, 0, $string_length), ' '));
                }

          $tpl->setCurrentBlock("rss_tech");
            $tpl->setVariable(array(
               "rss_tech.title" => $rss_title,
              "rss_tech.link" => $rss_link,
          ));
          $tpl->parseCurrentBlock();
        }
      }
       $html = $tpl->get();
      $tpl->free();           
     
      if ($CACHE_PAGES) {
        put_cached_page($cache_key, $cache_cat, $html, $cache_ttl);
      }     
           
   
    $html = str_replace('[SITE_BASEURL]', $SITE_BASEURL, $html);
    return str_replace('[COMMON.rss_tech]', $html, $pagecode);
  }


It's something to do with

$html = $tpl->get();
$tpl->free();

Thanks,
Andrew
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts

Kickstart
The Oracle



Joined: 04 Feb 2002
Karma :

PostPosted: 16:37 - 20 Jan 2009    Post subject: Reply with quote

Hi

Looks like the tpl object might not have been set up correctly (not that I tend to use OO stuff much).

Suspect the line:-

$tpl = make_template('common_elements/rss.html');

should be

$tpl = new make_template('common_elements/rss.html');

All the best

Keith
____________________
Traxpics, track day and racing photographs - Bimota Forum - Bike performance / thrust graphs for choosing gearing
 Back to top
View user's profile Send private message Send e-mail You must be logged in to rate posts
Old Thread Alert!

The last post was made 17 years, 271 days ago. Instead of replying here, would creating a new thread be more useful?
  Display posts from previous:   
This page may contain affiliate links, which means we may earn a small commission if a visitor clicks through and makes a purchase. By clicking on an affiliate link, you accept that third-party cookies will be set.

Post new topic   Reply to topic    Bike Chat Forums Index -> The Geek Zone All times are GMT + 1 Hour
Page 1 of 1

 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum

Read the Terms of Use! - Powered by phpBB © phpBB Group
 

Debug Mode: ON - Server: birks (www) - Page Generation Time: 0.16 Sec - Server Load: 1.15 - MySQL Queries: 14 - Page Size: 96.75 Kb