Home » Tutorials » Web Development » PHP » PHP and XML » How to open a news feed with fsockopen()..

How to open a news feed with fsockopen()

Added April 20, 2008, read 26 times

Learn to access a news feed using PHP.

Create a PHP file called fsockopen.php in the filesystem folder. If you just want to study the final code, use fsockopen.php in the download files for this chapter.

If your script editor automatically inserts a DOCTYPE declaration and XHTML skeleton, remove them. You need to start with a blank page. Insert the following code:

PHP Code
<?php
// create a socket connection
$remote = fsockopen('www.friendsofed.com', 80, $errno, $errstr, 30);
if (!$remote)
{
	// if no connection, display the error message and number
	echo "$errstr ($errno)";
}
else
{
	// otherwise communicate with remote server
}
?>

Select all 

This is the basic skeleton for any socket connection using fsockopen(). The only change you normally need to make is to the first argument, which is the domain name of the site that you want to access. If a connection can't be made, the first half of the conditional statement displays the error message and number. If the error number is 0, it may indicate the socket connections have been disabled on your server. In that event, consult your hosting company.

If a successful connection is made, the else clause is executed. At the moment, it contains just a comment. So let's fix that now.

First of all, you need to prepare a request and send it to the remote server. Add the ollowing code after the comment in the else clause:

PHP Code
// otherwise communicate with remote server
// prepare the request
$out = "GET /news.php HTTP/1.1\r\n";
$out .= "Host: www.friendsofed.com\r\n";
$out .= "Connection: Close\r\n\r\n";
// send the request
fwrite($remote, $out);
Select all

The request is stored in $out and consists of the following three elements:

The page you want, presented in this format: 

  • GET /path_to_page HTTP/1.1
  • The URL that we plan to open is www.friendsofed.com/news.php, which becomes just /news.php. Note that it begins with a forward slash. If you want the default page of a site, use a forward slash on its own.
  • Host, followed by a colon and the domain name.
  • An instruction to close the connection after the response has been sent.

Each part of the request must be followed by a carriage return and new line character \r\n), and the final line by an extra carriage return and new line character \r\n\r\n). Since these characters are PHP escape sequences, you need to use ouble quotes (see 'Using escape sequences with double quotes' in Chapter 3).

Once you have built the request, send it by passing $out to fwrite() with a reference o the remote connection that you have opened.

After sending the request, you need to capture the response in a variable, and then lose the socket connection. Add the following code to the else clause immediately elow the code in the previous step

PHP Code
// initialize a variable to capture the response
$received = '';
// keep the connection open until the end of the response
while (!feof($remote)) {
$received .= fgets($remote, 1024);
}
// close the connection
fclose($remote);
Select all

This uses feof(), fgets(), and fclose() in the same way as with local files. The nly difference is that I have added a second argument to fgets(). This tells the unction how many bytes to retrieve at a time. The fgets() function gets one line t a time, but some XML files don't use new lines, so it's more resource-efficient to pecify a length.

Finally, use echo to display the response from the remote server. Add the following line after the closing curly brace of the conditional statement:

PHP Code
echo $received;
Select all

Save fsockopen.php and load it into a browser. As long as you're connected to the Internet, you'll probably see the friends of ED news feed displayed as continuous plain text. To get a better understanding of what you have received, open the browse's source code view.

The disadvantage of using fsockopen() to access a remote data source is that you et all the HTTP headers, in addition to the news feed. If you scroll to the bottom of the source code view, you may also see some unwanted characters after the losing XML tag.

To get rid of the headers and any extraneous characters at the end of the feed, replace the line of code in step 5 with the following:

PHP Code
// find beginning and end of news feed
$start = strpos($received, '<?xml');
$endTag = '</rdf:RDF>';
$end = strpos($received, $endTag) + strlen($endTag);
// extract news feed and display
$clean = substr($received, $start, $end-$start);
echo $clean;
Select all

This uses the strpos() function to find the position of the beginning and end of he XML feed. At the time of this writing, the friends of ED news feed is enclosed in rdf:RDF> tags. Other feeds may use different tags, so you need to adjust the value of $endTag accordingly to find the end of the feed. The strpos() function returns he position of the first matching character in the substring that you're searching for, so to find the end position, you need to add the number of characters in the nd tag. The strlen() function is designed to do precisely that, so adding strlen($endTag) to the position of the first character of $endTag gives you the end of the feed.

Finally, the substr() function extracts the news feed. It takes three arguments: the riginal string, the position from which you want to start the extraction (the opening XML tag), and the number of characters (calculated in this case by subtracting $start from $end). 8. Save the page and reload it. Switch to your browser's source code view, and you should see the clean XML feed.

You need to use fsockopen() only if your hosting company has disabled allow_url_fopen. Once you have captured the remote data, you treat it as any other string. The easiest way to handle an XML news feed is with SimpleXML, which is available in PHP 5 and later. To learn more about SimpleXML, visit www.php.net/manual/en/ref.simplexml.php or see Beginning PHP and MySQL 5: From Novice to Professional by W. Jason Gilmore (Apress, ISBN: 1-59059-552-1).


Web Development Services

DirSphere

Football Tutorials

Business Listings

Free Online Games

Cheapest Car Insurance

Dish Network Deals

Best Web Hosting Reviews

Web Design Company

Discuss







Nobody posted any comments regarding this story. Be the first!