code_junkie

Best way to parse RSS/Atom feeds with PHP

Nov 12th, 2011
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. <?php
  2.  
  3. class BlogPost
  4. {
  5. var $date;
  6. var $ts;
  7. var $link;
  8.  
  9. var $title;
  10. var $text;
  11. }
  12.  
  13. class BlogFeed
  14. {
  15. var $posts = array();
  16.  
  17. function BlogFeed($file_or_url)
  18. {
  19. if(!eregi('^http:', $file_or_url))
  20. $feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $feed_or_url;
  21. else
  22. $feed_uri = $feed_or_url;
  23.  
  24. $xml_source = file_get_contents($feed_uri);
  25. $x = simplexml_load_string($xml_source);
  26.  
  27. if(count($x) == 0)
  28. return;
  29.  
  30. foreach($x->channel->item as $item)
  31. {
  32. $post = new BlogPost();
  33. $post->date = (string) $item->pubDate;
  34. $post->ts = strtotime($item->pubDate);
  35. $post->link = (string) $item->link;
  36. $post->title = (string) $item->title;
  37. $post->text = (string) $item->description;
  38.  
  39. // Create summary as a shortened body and remove images, extraneous line breaks, etc.
  40. $summary = $post->text;
  41. $summary = eregi_replace("<img[^>]*>", "", $summary);
  42. $summary = eregi_replace("^(<br[ ]?/>)*", "", $summary);
  43. $summary = eregi_replace("(<br[ ]?/>)*$", "", $summary);
  44.  
  45. // Truncate summary line to 100 characters
  46. $max_len = 100;
  47. if(strlen($summary) > $max_len)
  48. $summary = substr($summary, 0, $max_len) . '...';
  49.  
  50. $post->summary = $summary;
  51.  
  52. $this->posts[] = $post;
  53. }
  54. }
  55. }
  56.  
  57. ?>
Add Comment
Please, Sign In to add comment