Reading wordpress RSS feeds and inserting them in a PHP page.


fsockopen() function opens a connection to another host; it is a low level socket function for TCP other protocols ride on top of this connection.

<?php
$fp = fsockopen(“www.yourwordpresssite.com”, 80, $errno, $errstr, 30);

There is no http:// in front of the server name … this is a TCP connection to port 80 and we will supply the http information through this connection … this connection method works when others fail because it does not depend on libraries which might not be installed.

if (!$fp) {
echo “$errstr ($errno)<br />\n”;
} else {
$out = “GET /category/jquery-2/feed/ HTTP/1.1\r\n”;
$out .= “Host: http://www.yourwordpresssite.com\r\n”;
$out .= “Connection: Close\r\n\r\n”;

$out is the string of http data we will send. The first part of the http header that is sent is a get command which includes the page that is requested http version 1.1 also includes a host this may seem redundant however as the host is also the server name (the server name often is the IP address).

fwrite($fp, $out);
while (!feof($fp)) {
$contents .= fgets($fp, 128);
}
fclose($fp);
}

That is the request and we get all of the data into $contents in this example. When possible process the file in chunks in this case however it is an RSS feed which needs to be parsed. If we were providing the data for an AJAX request we would send the data as the server gets it.

Extract the item from the feed, within the item exists all the other elements of a post, we are only interested in the link, title and decriptioon.

preg_match_all( “/<item>(.+?)<\/item>/s”, $contents, $items);

foreach ($items[0] as $value) {
echo “<p>”;
preg_match( “/<link>(.+?)<\/link>/s”, $value, $temp);
echo “<a href=\””.$temp[1].”\”>”;

preg_match( “/<title>(.+?)<\/title>/s”, $value, $temp);
echo $temp[1].”</a>”;

preg_match( “/<description><\!\[CDATA\[(.+?)\]\]><\/description>/s”, $value, $temp);
//    echo “<br>”.$temp[1];
$temp = preg_replace(“/\&\#60\;(.+?)\&\#62\;/s”, “”, $temp[1]);
echo “<BR>”.preg_replace(“/<(.+?)>/s”, “”, $temp);

echo “\n<p>\n”;
}
?>

Remove encoded html and any raw html.

My preference is to use Perl but if you are adding information to a sidebar or other portion of a PHP page or PHP application then PHP is best.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: