PHP in HTML - RSS feeds.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bemaitea
Forum Newbie
Posts: 9
Joined: Sun Jul 04, 2010 6:21 pm

PHP in HTML - RSS feeds.

Post by bemaitea »

Hello all,

I have just a real simple query for those seasoned PHP devs out there. I'm new to PHP and coding in general, so don't take my naievte the wrong way!

Anyway, I am currently putting together a homepage for a website and I simply want to include 2 divs on the sidebar, one that updates itself with blog posts and another that updates itself with twitter posts via the resepective RSS feeds.

I've gone through various sites and found quite a few implementations of this and decided to try a php route since it is web crawler friendly, as opposed to a JS route.

My question is this: how do I use the php script with my already coded html?? :banghead: Can I embed php WITHIN the html document? Or can I have the server run the PHP first and then deliver the results to the html?

I know I can include html into the php file and have it be fine, but for such a small portion of the homepage I don't think it's the most efficient way. Plus I'd like my visitors to be able to land at 'index.html' rather than 'index.php'.

Any help for a newbie would be greatly appreciated!! :D
jraede
Forum Contributor
Posts: 254
Joined: Tue Feb 16, 2010 5:39 pm

Re: PHP in HTML - RSS feeds.

Post by jraede »

Files with the .php extension can be just html files with embedded PHP, using the php tags (<?php code_here ?>). So you could have your sidebar look like this:

Code: Select all

<div id="sidebar">
<?php php_code_here ?>
</div>
on a file called sidebar.php. You get the idea.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: PHP in HTML - RSS feeds.

Post by Christopher »

Yeah, and don't worry that it is "such a small portion of the homepage I don't think it's the most efficient way." The point of PHP is that it allows you to do stuff like this very easily. On the rare chance that you end with an actual performance problem then come back and ask how to solve that.
(#10850)
bemaitea
Forum Newbie
Posts: 9
Joined: Sun Jul 04, 2010 6:21 pm

Re: PHP in HTML - RSS feeds.

Post by bemaitea »

Thanks for the quick replies, jraede and christopher!

So essentially the suggestion here is to make the homepage go to 'index.php' and just have my HTML run normally within it, styles and all? Meaning I'd have my main content div with all my HTML and then have my sidebar div with the PHP running the appropriate script all within the index.php homepage.

Did I understand this correctly?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: PHP in HTML - RSS feeds.

Post by Christopher »

Yes.
(#10850)
bemaitea
Forum Newbie
Posts: 9
Joined: Sun Jul 04, 2010 6:21 pm

Re: PHP in HTML - RSS feeds.

Post by bemaitea »

Thanks for the clarification, Christopher! :D

So taking your guys' advice, I've gone ahead and just made my index.php with all the appropriate html and css stylings. As stated in this post, everything works perfectly fine! :D I have my site styled exactly as I want and now I have an automatically updating RSS feed thanks to the beauty of PHP!

Just for those who may stumble upon this at a later point, I used the AWESOME piece of free code written by Gary White found at http://apptools.com/phptools/xml/rss.php. It seems like he hasn't updated since 2005, but it works perfectly fine on my server. So big thanks to him!

The original scripting of the code echos the RSS as such:

<IMG>
<TITLE>< a href>
<pubdate> - <description>

Although I have very limited knowledge of PHP, I was able to feel my way around it and altered the output to:

<PUBDATE>
<title><a href>

However, at this moment the pubdate displays as: "D, d F Y H:i:s T"
It would be really nice to have the pubdate display as "F j s, Y" instead.

I've been sitting on this code for a few hours and can't figure it out! Can anyone out there shed some light?

Code is as follows:

Code: Select all

//classes follow

// Generic container for the complete RSS feed
class rssFeed{
	var $title="";
	var $copyright="";
	var $description="";
	var $image;
	var $stories=array();
	var $url="";
	var $xml="";
	var $link="";
	var $error="";
	var $maxstories=0;
	
	// public methods
	function parse(){
		$parser=xml_parser_create();
		xml_set_element_handler($parser, "startElement", "endElement");
		xml_set_character_data_handler($parser, "characterData");
		xml_parse($parser, $this->xml, true)
			or die(sprintf("XML error: %s at line %d", 
				xml_error_string(xml_get_error_code($parser)), 
				xml_get_current_line_number($parser)));
		xml_parser_free($parser);
	}

	function showHeading($tag=""){
		$tag=$tag?$tag:"h1";
		if($this->title)
			print "<$tag>$this->title</$tag>\n";
	}

	function showImage($align=""){
		$this->image->show($align);
	}

	function showLink(){
		if($this->link)
			print "<a href=\"$this->link\">$this->link</a>\n";
	}	
	function showDescription(){
		if($this->description)
			print "<p>$this->description</p>\n";
	}

	function showStories(){
		echo "<dl>\n";
		$n=0;
		foreach($this->stories as $story){
			$n++;
			if ($this->maxstories && $n>$this->maxstories)
				break;
			$story->show();
		}
		echo "</dl>\n";
	}
	
	// Methods used internally
	// Constructor: Expects one string parameter that is the URI of the RSS feed
	function rssFeed($uri=''){
		$this->image=new rssImage();
		if($uri){
			$this->url=$uri;
			$this->getFeed();
		} else {
			$this->error="No URL for RSS feed";
		}
	}
	
	// Retrieves the XML from the RSS supplier
	function getFeed(){
		// if we have a URL
		if ($this->url){
			if (extension_loaded('curl')) {
				$this->xml=$this->getRemoteFile($this->url);
			}
		}
	}

	function getRemoteFile($url){
		$s=new gwSocket();
		if($s->getUrl($url)){
			if(is_array($s->headers)){
				$h=array_change_key_case($s->headers, CASE_LOWER);
				if($s->error) // failed to connect with host
					$buffer=$this->errorReturn($s->error);
				elseif(preg_match("/404/",$h['status'])) // page not found
					$buffer=$this->errorReturn("Page Not Found");
				elseif(preg_match("/xml/i",$h['content-type'])) // got XML back
					$buffer=$s->page;
				else // got a page, but wrong content type
					$buffer=$this->errorReturn("The server did not return XML. The content type returned was ".$h['content-type']);
			} else {
				$buffer=$this->errorReturn("An unknown error occurred.");
			}
		}else{
			$buffer=$this->errorReturn("An unknown error occurred.");
		}
		return $buffer;
	}

	function errorReturn($error){
		$retVal="<?xml version=\"1.0\" ?>\n".
			"<rss version=\"2.0\">\n".
			"\t<channel>\n".
			"\t\t<title>Failed to Get RSS Data</title>\n".
			"\t\t<description>An error was ecnountered attempting to get the RSS data: $error</description>\n".
			"\t\t<pubdate>".date("D, d F Y H:i:s T")."</pubdate>\n".
			"\t\t<lastbuilddate>".date("D, d F Y H:i:s T")."</lastbuilddate>\n".
			"\t</channel>\n".
			"</rss>\n";
		return $retVal;
	}

	function addStory($o){
		if(is_object($o))
			$this->stories[]=$o;
		else
			$this->error="Type mismatach: expected object";
	}

}

class rssImage{
	var $title="";
	var $url="";
	var $link="";
	var $width=0;
	var $height=0;
	
	function show($align=""){
		if($this->url){
			if($this->link)
				print "<a href=\"$this->link\">";
			print "<img src=\"$this->url\" style=\"border:none;\"";
			if($this->title)
				print " alt=\"$this->title\"";
			if($this->width)
				print " width=\"$this->width\" height=\"$this->height\"";
			if($align)
				print " align=\"$align\"";
			print ">";	
			if($this->link)
				print "</a>";
		}
	}
}

class newsStory{
	var $title="";
	var $link="";
	var $description="";
	var $pubdate="";
	
	function show(){
		if($this->title){
			echo "<dt>";
			if($this->pubdate)
				echo "<i>$this->pubdate</i>";
			echo "</dt>\n";			
			if($this->link){
				echo "<dd><a href=\"$this->link\">$this->title</a></dd>\n";
			}elseif($this->title){
				echo "<dd>$this->title</a></dd>\n";
			}

		}
	}
}


class gwSocket{
	var $Name="gwSocket";
	var $Version="0.1";
	var $userAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
	var $headers;
	var $page="";
	var $result="";
	var $redirects=0;
	var $maxRedirects=3;
	var $error="";

	function getUrl( $url ) {
		$retVal="";
		$url_parsed = parse_url($url);
		$scheme = $url_parsed["scheme"];
		$host = $url_parsed["host"];
		$port = $url_parsed["port"]?$url_parsed["port"]:"80";
		$user = $url_parsed["user"];
		$pass = $url_parsed["pass"];
		$path = $url_parsed["path"]?$url_parsed["path"]:"/";
		$query = $url_parsed["query"];
		$anchor = $url_parsed["fragment"];

		if (!empty($host)){

			// attempt to open the socket
			if($fp = fsockopen($host, $port, $errno, $errstr, 2)){

				$path .= $query?"?$query":"";
				$path .= $anchor?"$anchor":"";

				// this is the request we send to the host
				$out = "GET $path ".
					"HTTP/1.0\r\n".
					"Host: $host\r\n".
					"Connection: Close\r\n".
					"User-Agent: $this->userAgent\r\n";
				if($user)
					$out .= "Authorization: Basic ".
						base64_encode("$user:$pass")."\r\n";
				$out .= "\r\n";

				fputs($fp, $out);
				while (!feof($fp)) {
					$retVal.=fgets($fp, 128);
				}
				fclose($fp);
			} else {
				$this->error="Failed to make connection to host.";//$errstr;
			}
			$this->result=$retVal;
			$this->headers=$this->parseHeaders(trim(substr($retVal,0,strpos($retVal,"\r\n\r\n"))));
			$this->page=trim(stristr($retVal,"\r\n\r\n"))."\n";
			if(isset($this->headers['Location'])){
				$this->redirects++;
				if($this->redirects<$this->maxRedirects){
					$location=$this->headers['Location'];
					$this->headers=array();
					$this->result="";
					$this->page="";
					$this->getUrl($location);
				}
			}
		}
		return (!$retVal="");
	}
	
	function parseHeaders($s){
		$h=preg_split("/[\r\n]/",$s);
		foreach($h as $i){
			$i=trim($i);
			if(strstr($i,":")){
				list($k,$v)=explode(":",$i);
				$hdr[$k]=substr(stristr($i,":"),2);
			}else{
				if(strlen($i)>3)
					$hdr[]=$i;
			}
		}
		if(isset($hdr[0])){
			$hdr['Status']=$hdr[0];
			unset($hdr[0]);
		}
		return $hdr;
	}

}

/*
	end of classes - global functions follow
*/

function startElement($parser, $name, $attrs) {
	global $insideitem, $tag, $isimage;
	$tag = $name;
	if($name=="IMAGE")
		$isimage=true;
	if ($name == "ITEM") {
		$insideitem = true;
	}
}

function endElement($parser, $name) {
	global $insideitem, $title, $description, $link, $pubdate, $stories, $rss, $globaldata, $isimage;
	$globaldata=trim($globaldata);
	// if we're finishing a news item
	if ($name == "ITEM") {
		// create a new news story object
		$story=new newsStory();
		// assign the title, link, description and publication date
		$story->title=trim($title);
		$story->link=trim($link);
		$story->description=trim($description);
		$story->pubdate=trim($pubdate);
		// add it to our array of stories
		$rss->addStory($story);
		// reset our global variables
		$title = "";
		$description = "";
		$link = "";
		$pubdate = "";
		$insideitem = false;
	} else {
		switch($name){
			case "TITLE":
				if(!$isimage)
					if(!$insideitem)
						$rss->title=$globaldata;
				break;
			case "LINK":
				if(!$insideitem)
					$rss->link=$globaldata;
				break;
			case "COPYRIGHT":
				if(!$insideitem)
					$rss->copyright=$globaldata;
				break;
			case "DESCRIPTION":
				if(!$insideitem)
					$rss->description=$globaldata;
				break;
		}
	}
	if($isimage){
		switch($name){
			case "TITLE": $rss->image->title=$globaldata;break;
			case "URL": $rss->image->url=$globaldata;break;
			case "LINK": $rss->image->link=$globaldata;break;
			case "WIDTH": $rss->image->width=$globaldata;break;
			case "HEIGHT": $rss->image->height=$globaldata;break;
		}
	}
	if($name=="IMAGE")	
		$isimage=false;
	$globaldata="";
}

function characterData($parser, $data) {
	global $insideitem, $tag, $title, $description, $link, $pubdate, $globaldata;
	if ($insideitem) {
		switch ($tag) {
			case "TITLE":
				$title .= $data;
				break;
			case "DESCRIPTION":
				$description .= $data;
				break;
			case "LINK":
				$link .= $data;
				break;
			case "PUBDATE":
			case "DC:DATE":
				$pubdate .= $data;
				break;
		}
	} else {
		$globaldata.=$data;
	}
}

?>

I'm sure it's something really simple that I'm missing. Any help would be appreciated!!
bemaitea
Forum Newbie
Posts: 9
Joined: Sun Jul 04, 2010 6:21 pm

Re: PHP in HTML - RSS feeds.

Post by bemaitea »

Hey guys,

Quick update!

Turns out the php script is actually just printing the output from the RSS feed's <pubdate>, which is in the unwanted format. So I guess I'll have to alter how the xml ouputs the <pubdate> instead of altering the PHP to re-interpret the <pubdate>.

Hope it's worth it.... :crazy:
Post Reply