Google API & php VIA soap

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Google API & php VIA soap

Post by hairyjim »

Hi all,

I have been wrestling with Google and SOAP for the last few days and well, it has took me 3 days to get PEAR / SOAP working just to find I can't get any results out of google for some bizarre reason.

The code is as follows:

Code: Select all

<?php

if (!$_POST&#1111;'q'])
&#123;
?>
	<h2>Search</h2>
	<form action="<?=$_SERVER&#1111;'PHP_SELF']?>" method="post">
	Search term: <input type="text" name="q">
  <input type="submit" name="Submit" value="Submit">
</form>
<?
&#125;
else
&#123;
	// include the class
	include("SOAP/Client.php");
	
	// create a instance of the SOAP client object
	$soapclient = new SOAP_Client('http://api.google.com/search/beta2');
	
	// set up an array containing input parameters to be
	// passed to the remote procedure
	$params = array(
	     'key' => 'MyKeyIsPrivate',   // Google license key
	     'q'   => $_POST&#1111;'q'],                          // search term
	     'start' => 0,                                  // start from result n
	     'maxResults' => 10,                            // show a total of n results
	     'filter' => true,                              // remove similar results
	     'restrict' => '',                              // restrict by topic
	     'safeSearch' => true,                          // remove adult links
	     'lr' => '',                                    // restrict by language
	     'ie' => '',                                    // input encoding
	     'oe' => ''                                     // output encoding
	);
	
	// invoke the method on the server
	$result = $soapclient->call("doGoogleSearch", $params, "urn:GoogleSearch"); 
	
	// print the results of the search
	if (PEAR::isError($result))
	&#123;
?>
  <h2>Error</h2>
  <? echo $result&#1111;'faultstring'];?>
<?	
	&#125;
	else
	&#123;
?>
  <h2>Search Results</h2>
  <? echo $result&#1111;'estimatedTotalResultsCount'] . " hits
found in " . $result&#1111;'searchTime'] . " ms"; ?>
  <ul>
<?
	if (is_array($result&#1111;'resultElements']))
	&#123;
  foreach ($result&#1111;'resultElements'] as $r)
  &#123;
  	echo "<li><a href=" . $r&#1111;'URL'] . ">" .
$r&#1111;'title'] . "</a>";
  	echo "<br>";
  	echo $r&#1111;'snippet'] . "(" . $r&#1111;'cachedSize'] .
")";
  	echo "<p>";
  &#125;
	&#125;
?>
  </ul>
<?
	&#125;
&#125;
?>
If I were to print_r($result); I get the array of results returned, obviously not in a nice format but it proves I get results.

What am I doing wrong here, I can't see the wood for the trees anymore....especially after trying to get Pear & SOAP up and running :evil:
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

when you print_r you see like searchTime => 234 or whatever? that is, its an associative array? It seems wierd how you are accesing $results. WHat is that thing anyways?
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

when you print_r you see like searchTime => 234 or whatever
Yeah sure do.
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

Which part doesn't work?? Does this line:

<? echo $result['estimatedTotalResultsCount'] . " hits
found in " . $result['searchTime'] . " ms"; ?>


and what sort of thing is $result['resultElements'];
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

and what sort of thing is $result['resultElements'];
[resultElements] - An array of [resultElement] items. This corresponds to the actual list of search results provided by google & API


Code: Select all

<?php
include("SOAP/Client.php");

// Google search query
$query = 'soap';

$s = new SOAP_Client('http://api.google.com/search/beta2');

// set up an array containing input parameters to be
// passed to the remote procedure
$params = array(
     'key' => 'MyGoogleKey',   // Google license key
     'q' => $query,                          			// search term
     'start' => 0,                                  // start from result n
     'maxResults' => 1,                            // show a total of n results
     'filter' => true,                              // remove similar results
     'restrict' => '',                              // restrict by topic
     'safeSearch' => true,                          // remove adult links
     'lr' => '',                                    // restrict by language
     'ie' => '',                                    // input encoding
     'oe' => ''                                     // output encoding
);
	
	// invoke the method on the server
	$result = $s->call('doGoogleSearch', $params, 'urn:GoogleSearch'); 

// Is result a PEAR_Error?
if (get_class($result) == 'pear_error')
&#123;
    $message = $result->message;
    $output = "An error occured: $message<p>";
&#125;
else
&#123;
    // We have proper search results
    $elements = $result&#1111;'resultElements'];
	$num = $result&#1111;'estimatedTotalResultsCount'];
    $list = '';
	//$num = '2';
    if ($num > 0) &#123;
        foreach ($elements as $item) &#123;
            $size = $item&#1111;'cachedSize'];
            $title = $item&#1111;'title'];
            $url = $item&#1111;'URL'];
            $snippet = $item&#1111;'snippet'];
            $desc = "<p><b>$title</b> - <a href="$url">$url</a>
<small>&#1111;Size: $size]</small></p>";
            $desc .= "\n<blockquote>$snippet</blockquote>\n\n";
            $list .= $desc;
        &#125;
    &#125;
    $output = "$num results returned:\n $list";
&#125;
print ($output);
echo "<br>";
echo "<pre>";
print_r($result);

?>
I have rehashed the code. I can print the array using print_r. This shows me I do get results and there is a value in [estimatedTotalResultsCount].

Now if I try and access [estimatedTotalResultsCount] via PHP:

Code: Select all

$num = $result&#1111;'estimatedTotalResultsCount'];
and then try and print the var to screen I get nothing.

So I beleive there is something wrong with the way I try and reference the array. But I am lost and do not know where to go next.

Help is greatly appreciated
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

what if you change ' to " or lose them altogether? I know you have it properly there, but its worth a shot and post the results of print_r
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

Well I tried with " and with ' and without either and nothing worked.

This is the output from print_r

There is only one result because I set google to only return 1 for the time being.

results returned:

stdClass Object
(
[directoryCategories] => Array
(
[0] => stdClass Object
(
[fullViewableName] => Top/Computers/Programming/Internet/Web_Services/SOAP
[specialEncoding] =>
)

)

[documentFiltering] => 1
[endIndex] => 1
[estimateIsExact] =>
[estimatedTotalResultsCount] => 2100000
[resultElements] => Array
(
[0] => stdClass Object
(
[URL] => http://www.w3.org/TR/soap/
[cachedSize] => 9k
[directoryCategory] => stdClass Object
(
[fullViewableName] =>
[specialEncoding] =>
)

[directoryTitle] =>
[hostName] =>
[relatedInformationPresent] => 1
[snippet] => W3C. Do not link to this page - Use dated versions of the documents. Latest SOAP versions. This page ... SOAP Version 1.2. Latest version ...
[summary] =>
[title] => SOAP Specifications
)

)

[searchComments] =>
[searchQuery] => soap
[searchTime] => 0.148977
[searchTips] =>
[startIndex] => 1
)
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

Hrmmm... and what do you get when you print $result['estimatedTotalResultsCount']; ? Is it just blank?
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

Code: Select all

print ($result&#1111;'estimatedTotalResultsCount']);
This outputs nothing.

Pear & Pear_soap must be working otherwise I would not get anything from the print_r($result);

...but there has to be something in the setup. The code looks good.
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

so what happens between print_r($result) and print ($result['estimatedTotalResultsCount']); that would cause it to break?

or

is print ($result['estimatedTotalResultsCount']); unable to pull that from the array? try echo "$result[estimatedTotalResultsCount]";
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

Nah nothing, zippo, diddly squat.

:(
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

man, you got problems!!
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

It is sooooo frustrating. I know the data is there but there just ain't anything coming through.

Hmmm - I may try and install NuSOAP and see if I can get my script to work with that.

I could turn this into a tech note for others if I ever solve it.
magicrobotmonkey
Forum Regular
Posts: 888
Joined: Sun Mar 21, 2004 1:09 pm
Location: Cambridge, MA

Post by magicrobotmonkey »

can you get soap to return a numeric array instead of an associative array? it would make for unreadable code, but it might let you get to the data? I have no idea whats going on with your script!
hairyjim
Forum Contributor
Posts: 219
Joined: Wed Nov 13, 2002 9:04 am
Location: Warwickshire, UK

Post by hairyjim »

Well I have not solved this, but instead I installed NuSOAP instead of PEAR: SOap and it all worked really well.

The only thing I can think could be wrong with PEAR soap is perhaps the build of SOAP that I used. I will try an older version and see if the problem exists.
Post Reply