Pulling backlinks from Google

Discussion in 'PHP' started by Christian Little, Mar 3, 2008.

  1. #1
    When you search Google for the number of links pointing to a website, it has the following string on the page:

    I want to extract that 431 into a variable in PHP, but I'm having trouble figuring out the code to do it. So far I have this:

    
    function checkGoogleBacklinks($url) {
    // takes in $url as a domain (i.e. example.com) and returns the number of Google backlinks
    
    $google_url = "http://www.google.ca/search?hl=en&q=link%3A+$url&btnG=Google+Search&meta=";
    $google_results = file_get_contents($google_url);
    
    // extract stuff
    
      return($backlinks);
    }
    
    Code (markup):
    The above code will take a url and load the page from Google, but I don't know how to pull the backlinks number out of the html code.


    I know it's going to take some sort of preg_match or something like but, but how do I do it?

    Thanks :)
     
    Christian Little, Mar 3, 2008 IP
  2. 007c

    007c Peon

    Messages:
    611
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You need to use regex to extract that "Results 1 - 10 of about*" link then assign it a variable then open that url you grabbed.
     
    007c, Mar 3, 2008 IP
  3. Christian Little

    Christian Little Peon

    Messages:
    1,753
    Likes Received:
    80
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Any chance you know the coding for it? I really suck at regex :(
     
    Christian Little, Mar 3, 2008 IP
  4. Christian Little

    Christian Little Peon

    Messages:
    1,753
    Likes Received:
    80
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I found the code that works, here it is if anybody wants it for their projects (note - this isn't my code, I found it on http://www.roscripts.com/Display_Google_backlinks_with_PHP-79.html):

    
    function google_backs($url){ 
        $site = fopen('http://www.google.com/search?q=link%3A'.urlencode($url),'r'); 
        while($cont = fread($site,1024657)){ 
            $total .= $cont; 
        } 
        fclose($site); 
        $match_expression = '/of about <b>(.*)<\/b> linking to/Us'; 
        preg_match($match_expression,$total,$matches); 
        return $matches[1]; 
    }
    
    Code (markup):
     
    Christian Little, Mar 3, 2008 IP