get google results with php

Discussion in 'PHP' started by amorph, Jun 14, 2007.

  1. #1
    Does anyone know a good script or piece of code that would return the first 10 results (links) for a given string?

    Thank you.
     
    amorph, Jun 14, 2007 IP
  2. Nefarious

    Nefarious Peon

    Messages:
    36
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    here is some code I have that you can add together to make it work.


    This is pregmatch string will get you all the links.
    $pregmatch= '/<h2 class=r><a href="(.*?)" class=l>/';
    PHP:
    This is the pregmatch command you can use to actually get the links out of the page.
    preg_match_all($pregmatch,$string,$links);
    PHP:

    Now all you need to do is get the google results page into a string and you can run the preg_match_all command to put all the links into an array.

    $string should be the contents of the google results page
    $links[1] will be all the links in an array.

    print_r($links[1]); <--to view them all
     
    Nefarious, Jun 15, 2007 IP
  3. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #3
    
    <?
    function first_google_results( $query )
    {
    	@preg_match_all( '~(<h2 class=r><a href="(.*?[^"])" class=l>(.*?)</a>.*?</h2>)~si', 
    					file_get_contents( sprintf( 'http://www.google.com/search?hl=en&q=%s&btnG=Google+Search', $query ) ), 
    					$links 
    	);
    	return array(
    		'anchors' => $links[3],
    		'href' => $links[2]
    	);
    }
    ?>
    <html>
    <head>
    	<title>Moogle - Mini Google</title>
    </head>
    <body>
    	<form action="" method="get">
    	<input type="text" name="q" /><input type="submit" value="Moogle Search" />
    	</form>
    	<?
    		if( $_GET and $_GET['q'] )
    		{
    			$google = first_google_results( rawurlencode( $_GET['q'] ) );
    			
    			foreach( $google['href'] as $num => $link )
    			{
    				printf( "%02d&nbsp;&nbsp;<a href=\"%s\">%s</a><br />\n", $num + 1, $link, $google['anchors'][ $num ] );
    			}	
    		}	
    	?>
    </body>
    </html>
    
    PHP:
     
    krakjoe, Jun 15, 2007 IP