Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Mar 2006
    Posts
    478
    Thanks
    3
    Thanked 0 Times in 0 Posts

    read webpage content in to a variable

    read web content via a weblink like

    http://www.site.com/?id=123

    what is the correct way to do this?

  • #2
    Regular Coder
    Join Date
    Oct 2004
    Posts
    104
    Thanks
    7
    Thanked 2 Times in 2 Posts
    You could do it like this:
    PHP Code:
    <?php

    $file 
    "http://www.example.com";

    $handle fopen($file"r");
    $contents '';
    while (!
    feof($handle)) {
      
    $contents .= fread($handle8192);
    }
    fclose($handle);

    // $contents will now contain the contents of the file

    ?>
    It's not been tested, but try it? I've basically pulled it from the PHP manual.
    Last edited by NeoPuma; 03-21-2009 at 12:46 PM.

  • #3
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,519
    Thanks
    114
    Thanked 110 Times in 109 Posts
    The only problem with doing it this way is you want to get the filesize of the file to read to tell the fread() function the size of file. Like so

    PHP Code:
    $contents .= fread($handlefilesize($file)); 
    However filesize() doesn't work on files that are not hosted on the same server that the script is running on. For instance i can get $filesize("my_file.txt") if my_file.txt is hosted on my server, but I can't get $filesize("http://www.example.com")

    A better way to do this is using the file_get_contents() function. Does the same thing but doesn't require to know the size of the file and is smaller code

    PHP Code:
    <?PHP
    $contents
    ='';
    $contents.=file_get_contents("http://www.example.com");
    echo 
    $contents;
    ?>
    Last edited by timgolding; 03-21-2009 at 01:40 PM.
    You can not say you know how to do something, until you can teach it to someone else.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •