Is there a way in PHP to "grab" the source of a web page?

by 10 replies
13
PROBLEM SOLVED- THANKS
Is there a (relatively simple) way in PHP to "grab" the source code of a web page (by URL) so that you can search it for text?

I want to access a web page's source code and confirm (or not) that a particular piece of code is present.

I want basically copy the manual process of:

opening a web page in the browser
choosing view page source
Find command "some text"
Get a true or false result.

All and any help gratefully received

Tony
#programming #grab #page #php #source #web
  • Yes, this is pretty easy:

    $content = file_get_contents("http://www.example.com/something.html");
    • [ 1 ] Thanks
  • <?php
    $stringtofind = "whatever you are looking for";
    $content = file_get_contents("http://www.domain.com/page.html");
    $pos = strpos($content,$stringtofind);

    if($pos === false) {
    // Not found
    }
    else {
    // Found
    }
    ?>
    • [ 1 ] Thanks
    • [1] reply
    • Thanks Micheal,
      I was Googling around for ages trying to find the command. Normally I don't have any problms finding this kind of stuff but for some reason I just could not pin it down. I thought it must be pretty straight forward.

      Many many Thanks

      Fantastic a complete solution. Exactly what I was after

      You guys Rock!
      • [1] reply
  • You can fetch the source code with file_get_contents(); function, and you can check if the code line is present with strpos();

    Here's the complete script sollution:

    <?

    // Enter the URL of the page that you want to view the source (replace page.com)

    $page = file_get_contents("http://www.page.com");

    // Enter code that you are looking for here (replace code)

    $search = "code";

    // Script will check if code is present on the source code of the URL

    $check = strpos($page,$search);

    // Post the results

    if($check == true)
    {
    echo "The code is found!";
    }
    else
    {
    echo "The code is not found!";
    }

    ?>

    P.S. Sorry I cannot wrap it in CODE tags, because code tags will remove the dollar variables, and script will get messy to understand...
    • [1] reply
    • Many thanks guys for all your help and advice. I now have exactly what I needed up and runnuing and its saving a me a mountain of time.

      I have used the PHP solution not the cURL solution. Simply because I understod teh PHP solution.

      Never seen cURL before and looked lie I would need a little time to understand it so speed and simplicity won the day.

      This is only a rough working model so when I eventualy get someone to do the job properly I'll let them worry about the coding

      Thanks again guys
      Problem solved.
      • [1] reply

Next Topics on Trending Feed