Subscribe to How-To Geek

PHP: Get the contents of a web page, RSS feed, or XML file into a string variable

You will often have the need to access data that resides on another server, whether you are writing an online RSS aggregator or doing screen scraping for a searching mechanism. PHP makes pulling this data into a string variable an extremely simple process.

You can go with the really short method:

$url = "http://www.howtogeek.com";

$str = file_get_contents($url);

 

The only problem with that method is that some web hosts have url access blocked in the file methods, for security reasons. You may be able to use this workaround method instead:

 

function get_url_contents($url){
        $crl = curl_init();
        $timeout = 5;
        curl_setopt ($crl, CURLOPT_URL,$url);
        curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $ret = curl_exec($crl);
        curl_close($crl);
        return $ret;
}

You should now have the contents of the website in a string variable. Note that this doesn't pull down the supporting files such as javascript or CSS. You will have to further parse the page and retrieve those seperately if you need the whole thing.

The Geek is the founder of How-To Geek and a geek enthusiast. When he's not coming up with great how-to articles, he's probably writing at his personal blog. This article was written on 09/25/06 and tagged with: Programming, PHP

Comments (2)

  1. Demetrius

    Problem with RSS Feed in WordPress.
    I have a subdomain that I installed wordpress for another blog site, but the subdomain site's rss feed points to my parent site.
    Can anyone come up with any suggestions?

  2. Davide

    Hi,

    I've tried your hack but I always get the same result:

    "Destination host forbidden"

    How can I solve this issue?

    Thanks.


Leave a Comment




Leave your friendly comment here. If you have a computer help question, leave it on the forums instead.

Note: Your comment may not show up immediately on the site.

Sponsored Links
Getting Started
About How-To Geek
Popular Articles

Copyright © 2006-2008 HowToGeek.com. All Rights Reserved.