Search code examples
phpperllwp-useragent

Downloading a webpage source code from another one of my websites in PHP


I am more of a Perl programmer, learning PHP still...

I have this code in Perl that I can use to download source code of one of my other pages, or any page I want...

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
$ua->agent("Mozilla/8.0"); # act like we are very capable browser
$ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt", autosave => 1 });
#   $ua->cookie_jar(HTTP::Cookies->new(file => "lwpcookies.txt"));
$req = HTTP::Request->new(GET => "http://www.yahoo.com/");
#   $req->header('Accept' => 'text/plain');
$req->referer('http://www.yahoo.com/');
# send request
$res = $ua->request($req);
if ($res->is_success) {
    my $_tableContent = $res->content; # This gets the page content and fills it into the variable $_tableContent...
 ....

My question is, is there a way to do that in Php as easy as that? Or even easier?

Thank you. -Rich


Solution

  • You can fetch a page using file_get_contents() function, if URL wrapper is enabled and you don't need to pass additional headers, store cookies, etc.:

    $page_contents=file_get_contents("http://example.com/");
    

    Otherwise you can do it using CURL. Follow this topic: How to get page content using cURL?