Although we use RSS feeds or XML feeds for content syndication or better yet a Web Service, there will be times when you will be required to syndicate or read simple text blocks for your own consumption on another website or for your friend’s. You do want to cache the contents locally to avoid fetching it from remote server for every request. It will not just save the bandwidth for both, but also decrease loading times.
Accomplishing this in php is quite straight forward & here’s how you can easily read the contents of a remote file and write it locally for later retrieval.
Read the contents of remote file and cache it locally
Before you could display the contents of remote file on your website, you need to first get the contents and write them in a local file. Just define the remote_url and local_file and you are away. Make sure local file has writeable permission, chmod it to 666 before you run the following script:
function fetch_feed($remote, $local){
$contents=file_get_contents($remote); //fetch data feed
$fp=fopen($local, "w");
fwrite($fp, $contents); //write contents of feed to local file
fclose($fp);
}
$remote_url = 'http://www.remote-website.com/data.txt';
$local_file = dirname(__FILE__).'/cache/data.txt';
fetch_feed($remote_url, $local_file);
Read the contents of local file using php
You can now read and show the contents of local file to your web page using following snippet:
$fh = fopen( $local_file, 'r');
$data = fread($fh, filesize( $local_file));
fclose($fh);
echo 'Latest Data
';
echo $data;
Hope that helps!
Cheers.