PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Searching Google With The Google API

Handling The Returned Data From The Web Service

There is a quite a bit of information returned from performing a search with the API. We will only cover the essentials – if you’re really interested, you can simple var_dump() the results to see what else is available:

Listing 3 listing-3.php
<?php
    var_dump($result);
?>

The returned data contains an array called resultElements, which contain the returned results. So if this array is empty, there were no results. To output them, we simply loop over this array and output each one.

Each result element contains the following data:

  • URL — the URL of the web site
  • title — the title of the web site
  • snippet — a brief summary of the web site content

There are other fields it contains, that we don’t need right now.

Additionally, the returned data contains the following:

  • searchQuery — the search that was performed
  • estimatedTotalResultsCount — the number of results (approximately) the search yielded
  • startIndex — the position in the search of the first returned result (e.g. if we were fetching page 2)
  • endIndex — the position in the search of the last returned result
  • searchTime — the time in seconds it took Google to perform the search

Now, using all this data we can output the search results:

Listing 4 listing-4.php
<?php
    $numResults = count($result['resultElements']);
?>
<p>
    Search term: <strong><?= $result['searchQuery'] ?></strong>
</p>
<?php if ($numResults) == 0) { ?>
    <p>
        Your search yielded no results.
    </p>
<?php } else { ?>
    <p>
        Results <?= $result['startIndex'] ?> to <?= $result['endIndex'] ?>
        of <?= $result['estimatedTotalResultsCount'] ?>
    </p>
 
    <?php foreach ($result['resultElements'] as $row) { ?>
        <h3><a href="<?= $row['URL'] ?>"><?= $row['title'] ?></a></h3>
        <p>
            <?= $row['snippet'] ?>
        </p>
        <p>
            <?= $row['URL'] ?>
        </p>
    <?php } ?>
<?php } ?>

And that’s all there is to it!

Now we can combine this with a simple search form to create our own Google frontend. This file will be our google.php file.

In This Article