Jump to content


Photo
- - - - -

Easy Google Searching using PHP


  • Please log in to reply
4 replies to this topic

#1 TerrorKalle

TerrorKalle

    Young Padawan

  • Members
  • Pip
  • 6 posts

Posted 30 October 2006 - 06:04 PM

Easy Google Searching using PHP


Hey out there

Time for another script from me :o, well this one will allow you to search on Google using a class with some functions i've just finish putting together =)

Lets start out by making the class and then explain the functions and last some examples.

The Class:


<?php
	/**
	 * ============================================================	*
	 * Google Search Class Parser					*
	 * ============================================================	*
	 *  @File:	googlesearch.php				*
	 *  @Version:	1.0						*
	 *  @Author:	Kalle Sommer Nielsen				*
	 * ============================================================	*/

	class GoogleSearch
	{
		var $query	= '';
		var $local	= '';

		var $num	= 10;

		var $start	= 0;
		var $safe	= 0;
		var $spell	= 0;

		var $didyoumean	= false;
		var $spellitem	= '';

		var $results	= Array();

		function GoogleSearch($query = '', $start = 0, $num = 10, $safe = 0, $spell = 0, $local = 'en')
		{
			$this->query = $query;
			$this->local = $local;

			$this->num = $num;

			$this->start = $start;
			$this->safe = $safe;
			$this->spell = $spell;
		}

		function setQuery($query)
		{
			$this->query = $query;
		}

		function setLocal($local)
		{
			$this->local = $local;
		}

		function setSafe($safe)
		{
			$this->safe = $safe;
		}

		function setStart($start)
		{
			$this->start = $start;
		}

		function setSpell($spell)
		{
			$this->spell = $spell;
		}

		function setNum($num)
		{
			$this->num = $num;
		}

		function getQuery()
		{
			return($this->query);
		}

		function getLocal()
		{
			return($this->local);
		}

		function getSafe()
		{
			return($this->safe);
		}

		function getStart()
		{
			return($this->start);
		}

		function getSpell()
		{
			return($this->spell);
		}

		function getSpellInfo()
		{
			$spell = Array(
					'spell'	=> $this->didyoumean, 
					'item'	=> $this->spellitem
					);

			return($spell);
		}

		function getNum()
		{
			return($this->num);
		}

		function set($var, $val)
		{
			eval("\$this->" . $var . " = \$val;\";");
		}

		function get($var)
		{
			eval("return(\"\$this->" . $var . "\");");
		}

		function getAll()
		{
			$all = Array(
					'query'		=> $this->query, 
					'local'		=> $this->local, 
					'safe'		=> $this->safe, 
					'start'		=> $this->start, 
					'spell'		=> $this->spell, 
					'num'		=> $this->num
					);

			return($all);
		}

		function getSearchResults()
		{
			return($this->results);
		}

		function numSearchResults()
		{
			return(count($this->results));
		}

		function cleanCache()
		{
			$this->results = '';
			$this->results = Array();
		}

		function performSearch()
		{
			$this->cleanCache();

			if($this->num > 100)
			{
				$this->num = 100;
			}
			elseif($this->num < 1)
			{
				$this->num = 1;
			}

			if($this->getSpell())
			{
				$spell = "&spell= " . $this->spell;
			}

			$lang = ($this->local) ? '&hl=' . $this->local : '';
			$safe = "&safe=";
			$safe .= ($this->safe) ? 'on' : 'off';
			$num = "&num=" . $this->num;
			$start = "&start=" . $this->start . "&sa=N";

			$extra = $lang . $safe . $spell . $num . $start;

			$index = @file_get_contents('http://www.google.com/search?q=' . urlencode($this->query) . $extra);

			ob_start();
			echo($index);
			$search = ob_get_contents();
			ob_end_clean();

			$search = str_replace(' bgcolor=#ffffff topmargin=3 marginheight=3', '', $search);
			$search = preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $search);

			if(strstr($search, "&oi=spell&"))
			{
				$this->didyoumean = true;
			}

			$resultsrow = explode('<p class=g>', $search);

			$counter = 0;
			$parsed = Array();
			$newparsed = Array();

			foreach($resultsrow as $result)
			{
				if($counter != 0 && !in_array($counter, Array(10, 11)))
				{
					$parsed[] = $result;
				}
				elseif($counter == 10)
				{
					$res = explode('<br clear=all>', $result);
					$parsed[] = $res[0];
				}
				elseif($counter == 11)
				{
					break;
				}

				++$counter;
			}

			$counter = 0;

			foreach($parsed as $newparse)
			{
				$newparse = explode('</nobr>', $newparse);
				$newparse = $newparse[0];

				$begin = explode('<a class=l href="', $newparse);
				$begin = explode('">', $begin[1]);

				$newparsed[$counter]['url'] = $begin[0];

				$begin[1] = str_replace(Array('<b>', '</b>'), Array('', ''), $begin[1]);
				$begin = explode('</a>', $begin[1]);

				if($newparsed[$counter]['url'] == $begin[0])
				{
					$begin[0] = '';
				}

				$newparsed[$counter]['title'] = $begin[0];

				$begin = explode('<br>', $begin[1]);
				$begin[0] = str_replace('<table cellpadding=0 cellspacing=0 border=0><tr><td class=j><font size=-1>', '', $begin[0]);

				if($begin[0]{0} == '<')
				{
					$begin[0] = '';
				}

				$newparsed[$counter]['description'] = $begin[0];

				++$counter;
			}

			$this->results = $newparsed;
		}
	}
?>


Same that as what you like, i choosed "googlesearch.class.php".


Class functions

GoogleSearch::GoogleSearch($query, $start, $num, $safe, $spell, $local)
  • $query = The query to be executed on Google
  • $start = Where to start on listing results, default is 0
  • $num = How many results per page, max 100. default is 10
  • $safe = Enable google safe search, default is 0
  • $spell = If you have used spell check on your results, then set this to 1 to prevent google from saying "Did you mean xxx?"
  • $local = Local language you want to search on, eg. da for danish. default is 'en'
Follwing functions sets / changes options set by the constructor above


GoogleSearch::setQuery($query)
  • $query = New query to be executed
GoogleSearch::setLocal($local)
  • $local = New local area to search in
GoogleSearch::setSafe($safe)
  • $safe = Change google safe search method
GoogleSearch::setStart($start)
  • $start = New starting row to list results from
GoogleSearch::setSpell($)
  • $spell = Change google spell check from being used
GoogleSearch::setNum($num)
  • $num = Set how many results you want returned
Following functions returns info about them selves using the options set above


GoogleSearch::getQuery()
  • Returns given query string
GoogleSearch::getLocal()
  • Returns given local area string
GoogleSearch::getSafe()
  • Returns true if using Google safe search, false otherwise
GoogleSearch::getStart()
  • Returns on where to start listing results by
GoogleSearch::getSpell()
  • Returns if you have disabled or enabled the spell check, true if enabled false otherwise
GoogleSearch::getSpellInfo()
  • Returns info about spelling (only if on, and what google suggest you could search on)
GoogleSearch::getNum()
  • Returns how many results you want per page
Miscellaneous functions:


GoogleSearch::getAll()
  • Returns all configuration variables set from the constructor/set functions
GoogleSearch::set($var, $val)
  • $var = Variable to set (query, local, safe, start, spell or num)
  • $val = New value
GoogleSearch::get($var)
  • Returns value of $var, given from the constructor/set functions
Search functions:


GoogleSearch::getSearchResults()
  • Returns search results (First when you have "performed" a search)
GoogleSearch::numSearchResults()
  • Returns the number of returned results
GoogleSearch::cleanCache()
  • Clear search cache
GoogleSearch::performSearch()
  • Performs the search
About Google Spell check:
The spell function (GoogleSearch::getSpellInfo()) will only return an result if you're on page on (mean you starting the search from $start 0, default), this function also returns an array. First array item ("spell") is set to true if google suggest something and the other array item ("item") is what google suggest you to search on. example:


<?php
	// Assuming that $google is the an "GoogleSearch" Object and a
	// search has been performed...

	$spell = $google->getSpellInfo();

	if($spell['spell'])
	{
		echo("Google suggest you to search on: " . $spell['item']);
	}
?>



Examples of usage:

A Normal standard search:
This small example is using the default search options set by the GoogleSearch::GoogleSearch() constructor function, we are searching on "Free ClanTemplates":


<?php
	// Include class
	require_once('./googlesearch.class.php');

	// Construct
	$google =& new GoogleSearch();

	// Set query
	$google->setQuery("Free ClanTemplates");

	// Perform search
	$google->performSearch();

	// Run a loop and display the results
	foreach($google->getSearchResults() as $result)
	{
		echo("
			<p />
				<div style=\"width: 600px;\">
					<h3>" . $result['title'] . "</h3>
					" . $result['description'] . "<br />
					<a href=\"" . $result['url'] . "\" target=\"_new\">" . $result['url'] . "</a>
				</div>
			");
	}

	// Shutdown
	$google = null;
?>


Exampe output:


<p />
				<div style="width: 600px;">
					<h3>Free Clan Gaming Templates - Clantemplates.com</h3>
					Templates for online gaming clans for games with multiplayer options. Counterstrike, Call of Duty, Half Life, Halo, Joint Operations, fonts, tutorials, ...<br />
					<a href="http://www.clantemplates.com/" target="_new">http://www.clantemplates.com/</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Free Masons Template by Knightmare @ Clantemplates.com</h3>
					latest files; latest news; Latest information. home sep team sep Results sep Files sep Forums sep Contact Us sep History sep. Clan Templates.com ...<br />
					<a href="http://clantemplates.com/templates/rainbow6_freemasons/" target="_new">http://clantemplates.com/templates/rainbow6_freemasons/</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Ultima Online [FREE] - ClanTemplates Forums</h3>
					Ultima Online [FREE] Gamers Edge. ... Go Back, ClanTemplates Forums > Community > Gamers Edge · Reload this Page Ultima Online [FREE] ...<br />
					<a href="http://forums.clantemplates.com/showthread.php?t=51062" target="_new">http://forums.clantemplates.com/showthread.php?t=51062</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Blogging and Pinging- Powerful Backdoor Into Major Search Engines ...</h3>
					Blogging and Pinging- Powerful Backdoor Into Major Search Engines For Free/ Articles. ... Go Back, ClanTemplates Forums > Professional > Articles ...<br />
					<a href="http://forums.clantemplates.com/showthread.php?p=1056091" target="_new">http://forums.clantemplates.com/showthread.php?p=1056091</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Free Gaming Clan Templates</h3>
					QUOTE(spistols678 @ Apr 9 2005, 12:28 PM). http://www.clantemplates.com pretty good site for gaming templates, for free but you have to link back to them. ...<br />
					<a href="http://www.astahost.com/info.php/free-gaming-clan-templates_t4221.html" target="_new">http://www.astahost.com/info.php/free-gaming-clan-templates_t4221.html</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Xtream-Team-Clan / XTC Designs</h3>
					<br />
					<a href="http://www.xtream-team-clan.de/Xtream-Team-Clan/index.php?site=files&cat=2" target="_new">http://www.xtream-team-clan.de/Xtream-Team-Clan/index.php?site=files&cat=2</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Free Clantemplates by Weddig & Keutel</h3>
					<br />
					<a href="http://weddig-keutel.de/_mod.clan-var0.freetemplates" target="_new">http://weddig-keutel.de/_mod.clan-var0.freetemplates</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Free Clan Templates</h3>
					Here are some sites with Free Clan Templates, some are very nice and useful for your clan website. www.clantemplates.com www.thedesignworld.com ...<br />
					<a href="http://www.trap17.com/index.php/free-clan-templates_t36100.html" target="_new">http://www.trap17.com/index.php/free-clan-templates_t36100.html</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>ClanSuite.com - just a eSport CMS | free clan cms, content ...</h3>
					We also provide free clantemplates within our cms. Those free templates are mostly provided by the community made by high tech computers. ...<br />
					<a href="http://www.clansuite.com/" target="_new">http://www.clansuite.com/</a>
				</div>
			
			<p />
				<div style="width: 600px;">
					<h3>Twisted Creations - Links</h3>
					Free Clantemplates (772 hits), Jme. Down Under Racing NFS clan site (398 hits), DURxLoRdHSV. Driving Tone A mixed genre rock band in the West Midlands area ...<br />
					<a href="http://ldu.twstc.com/links.php?c=links" target="_new">http://ldu.twstc.com/links.php?c=links</a>
				</div>


Search using google spell check (Remember you can set spell check off using GoogleSearch::setSpell() to 0):
An exampe showing how easy it is to use the Google Spell check, we search on "prodict" with 3 results:


// Include class
	require_once('./googlesearch.class.php');

	// Construct
	$google =& new GoogleSearch();

	// Set query
	$google->setQuery("Free ClanTemplates");

	// Set max results to 3
	$google->setNum(3);

	// Perform search
	$google->performSearch();

	// Run a loop and display the results
	foreach($google->getSearchResults() as $result)
	{
		echo("
			<p />
				<div style=\"width: 600px;\">
					<h3>" . $result['title'] . "</h3>
					" . $result['description'] . "<br />
					<a href=\"" . $result['url'] . "\" target=\"_new\">" . $result['url'] . "</a>
				</div>
			");
	}

	// Spell check
	$spellinfo = $google->getSpellInfo();

	if($google->getStart() == 0 && $spellinfo['spell'])
	{
		echo("
			<p style=\"border-top: 3px solid #000000;\">
				<span style=\"color: red;\">Did you mean: " . $spellinfo['item'] . "?</span>
			");
	}

	// Shutdown
	$google = null;
?>


Note that the Spell thing isnt working very well, so it might give lots of errors, my suggestion until I come out with a new version that fixes this is to not using it :o

Cheers,
Kalle


  • AaMuckedGr likes this

#2 Adαm

Adαm

    Young Padawan

  • Members
  • Pip
  • 189 posts
  • Gender:Male
  • Location:United Kingdom

Posted 01 November 2006 - 11:34 AM

Wow, again it looks awesome. Good job :)

#3 felguard

felguard

    Young Padawan

  • Members
  • Pip
  • 21 posts

Posted 02 November 2006 - 03:43 AM

Quick question, is this kind of simliar to this?

http://www.google.com/searchcode.html

#4 TerrorKalle

TerrorKalle

    Young Padawan

  • Members
  • Pip
  • 6 posts

Posted 02 November 2006 - 06:56 PM

Quick question, is this kind of simliar to this?

http://www.google.com/searchcode.html

Not quite, this piece of code allows you to totally customizing the search on your website, also without having your visitor to go to Google.com/search?too=long&query=string&that=nobody&will=remember, which will make it alot more user friendly :mellow:

#5 Chaos King

Chaos King

    Senior Programmer

  • P2L Staff
  • PipPipPip
  • 676 posts
  • Gender:Male
  • Location:Florida

Posted 03 January 2007 - 11:41 PM

Interesting concept, I would make it so that it tires to use cURL first if it is installed and if that fails, use file_get_contents since cURL is a by far a lot faster. But thats just me, still a nice class.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users