Display RSS news feed
-
Resolved
Here’s a little code I wrote up that will parse and display a RSS news feed nicely. You can see it in action here: https://www.blog.jydesign.biz Note the stuff on the right about latest funny stuff. That’s a RSS new feed.
Here’s the code. Add into index.php Not sure how to use myhacks.php yet, anyone with any pointers will be greatly apprecipated.
<li id=”news”>Latest News-
<?php
// Global variables for function use.
$GLOBALS[‘title’] = false;
$GLOBALS[‘link’] = false;
$GLOBALS[‘description’] = false;
$GLOBALS[‘titletext’] = null;
$GLOBALS[‘linktext’] = null;
$GLOBALS[‘desctext’] = null;
$GLOBALS[‘counter’] = 0;
// function: startElement
// Deals with the starting element
function startElement( $parser, $tagName, $attrs ) {
// By setting global variable of tag name
// I can determine which tag I am currently
// parsing.
switch( $tagName ) {
case ‘TITLE’:
$GLOBALS[‘title’] = true;
break;
case ‘LINK’:
$GLOBALS[‘link’] = true;
break;
case ‘DESCRIPTION’:
$GLOBALS[‘description’] = true;
break;
}
}
// function: endElement
// Deals with the ending element
function endElement( $parser, $tagName ) {
// By noticing the closing tag,
// I can print out the data that I want.
switch( $tagName ) {
case ‘TITLE’:
$GLOBALS[‘counter’]++;
if ($GLOBALS[‘counter’] > 2) {
echo “<br>”;
}
$GLOBALS[‘title’] = false;
//$GLOBALS[‘titletext’] = “”;
break;
case ‘LINK’:
if ($GLOBALS[‘counter’] > 2) {
echo “” . $GLOBALS[‘titletext’][$GLOBALS[‘counter’] – 1] . “<br>”;
}
$GLOBALS[‘link’] = false;
$GLOBALS[‘linktext’] = “”;
break;
/*case ‘DESCRIPTION’:
echo “Desc: ” . $GLOBALS[‘desctext’] . “”;
$GLOBALS[‘description’] = false;
$GLOBALS[‘desctext’] = “”;
break;*/
}
}
// function: charElement
// Deals with the character elements (text)
function charElement( $parser, $text ) {
// Verify the tag that text belongs to.
// I set the global tag name to true
// when I am in that tag.
if( $GLOBALS[‘title’] == true ) {
$GLOBALS[‘titletext’][$GLOBALS[‘counter’]] .= $text;
} else if( $GLOBALS[‘link’] == true ) {
$GLOBALS[‘linktext’] .= trim( $text );
} else if( $GLOBALS[‘description’] == true ) {
$GLOBALS[‘desctext’] .= htmlspecialchars( trim( $text ) );
}
}
// Create an xml parser
$xmlParser = xml_parser_create();
// Set up element handler
xml_set_element_handler( $xmlParser, “startElement”, “endElement” );
// Set up character handler
xml_set_character_data_handler( $xmlParser, “charElement” );
// Open connection to RSS XML file for parsing.
$fp = fopen( “https://www.fun-emails.org/backend.php”, “r” )
or die( “Cannot read RSS data file.” ); // Change the link to the link to your RSS feed.
// Parse XML data from RSS file.
while( $data = fread( $fp, 4096 ) ) {
$data = str_replace(“‘”, “'”, $data);
xml_parse( $xmlParser, $data, feof( $fp ) );
}
// Close file open handler
fclose( $fp );
// Free xml parser from memory
xml_parser_free( $xmlParser );
?>
- The topic ‘Display RSS news feed’ is closed to new replies.