SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 31

Thread: google web API

  1. #1
    PHP warrior dkode's Avatar
    Join Date
    Sep 2001
    Location
    Planet Namek
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    google web API

    i am attempting to use the google web API to grab results from google via php. heres my code:

    PHP Code:
    <html>
    <head><basefont face="Arial"></head>
    <body>
    <?php

    if (!$_POST['q']) {
    ?>
        <h2>Search</h2>
        <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Search term: <input type="text" name="q">
        </form>
    <?
    }
    else {
        
    // 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' => 'MY_GOOGLE_KEY',   // Google license key
             
    'q'   => $_POST['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)) {
            
    ?>
            <h2>Error</h2>
            <? echo $result['faultstring'];?>
            <?
        
    }
        else {
            
    ?>
            <h2>Search Results</h2>
            <? echo $result['estimatedTotalResultsCount'] . " hits found in " $result['searchTime'] . " ms"?>


    <ul>
            <?        
            
    if (is_object($result['resultElements'])) {
                echo 
    "within first if<br>";
                echo 
    "result: $result<br>";
                echo 
    "deeper: $result[resultElements]<br>\n";
                foreach (
    $result['resultElements'] as $r) {
                    echo 
    "<li><a href=" $r['URL'] . ">" $r['title'] . "</a>";
                    echo 
    "<br>";
                    echo 
    $r['snippet'] . "(" $r['cachedSize'] .")";
                    echo 
    "<p>";
                }
            }
            
    print_r($result);
            
    ?>
            </ul>



            <?
        
    }
    }
    ?>
    </body>
    </html>
    now i can see everything when i do print_r($result); but $result comes out as : stdClass Object instead of an array like in the tutorial on devshed. This prevents me from outputting the results via a foreach loop or even that if(is_array...) won't enter. What is a stdClass Object? i've never seen that before.

  2. #2
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You mean this tutorial right? I'll check it out shortly, if no one gets there first.

  3. #3
    PHP warrior dkode's Avatar
    Join Date
    Sep 2001
    Location
    Planet Namek
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thats correct,

    in the tutorial they show the results they got from google in the $result variable being an array. But when I attempt to grab the results, $results is a stdClass Object?

    strange. a couple of other tutorials on the web show the same thing.

  4. #4
    Mlle. Ledoyen silver trophy seanf's Avatar
    Join Date
    Jan 2001
    Location
    UK
    Posts
    7,168
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Stupid question first! You are using a valid license yeah?

    Sean
    Harry Potter

    -- You lived inside my world so softly
    -- Protected only by the kindness of your nature

  5. #5
    PHP warrior dkode's Avatar
    Join Date
    Sep 2001
    Location
    Planet Namek
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yes, i registered with them and made a key, i put it in. another strange thing is I am getting a result, i just cant get it at for some reason. when i do print_r($result); I get the following:

    this is only the first 15 lines or so
    Code:
    stdClass Object
    (
        [documentFiltering] => 
        [estimatedTotalResultsCount] => 4740000
        [directoryCategories] => Array
            (
                [item] => stdClass Object
                    (
                        [specialEncoding] => 
                        [fullViewableName] => Top/Recreation/Pets/Cats
                    )
    
            )
    
        [searchTime] => 0.151481
        [resultElements] => Array
            (
                [0] => stdClass Object
                    (
                        [cachedSize] => 9k
                        [hostName] => 
                        [snippet] => lib-web-<b>cats</b>. library Web pages, online catalogs, and profiles. a directory<br> of over 5,000 libraries worldwide. Maintained by Marshall Breeding <b>...</b>   
                        [directoryCategory] => stdClass Object
                            (
                                [specialEncoding] => 
                                [fullViewableName] => Top/Reference/Libraries/Online_Catalogs/Directories
                            )
    
                        [relatedInformationPresent] => 1
                        [directoryTitle] => lib-web-<b>cats</b> 
                        [summary] => Searchable database of over 4500 library web sites and online catalogs worldwide. 
                        [URL] => http://staffweb.library.vanderbilt.e...ibwebcats.html
                        [title] => lib-web-<b>cats</b>: Search Results
                    )
    as you can see i do receive $result['resultElements'] array which contains all the matches, when i attempt to test:

    PHP Code:
    if (is_array($result['resultElements']) {
        
    // something here

    it doesnt evaluate true, even though i see it when i print_r($result);

  6. #6
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm - sounds a little like either Google changed their API since the tutorial was written or there's a mistake in the tutorial. On of SOAPs features is you can pass whole objects with it.

    Might be worth checking over this tutorial on the Google API. It's written for Java but might give you hints.

  7. #7
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    its an array of objects ...
    try this:
    PHP Code:
    foreach ($result['resultElements'] as $r) {
                    echo 
    "<li><a href=" $r->URL ">" $r->title "</a>";
                    echo 
    "<br>";
                    echo 
    $r->snippet "(" $r->cachedSize .")";
                    echo 
    "<p>";
                } 
    Last edited by AcidReign; Jul 21, 2002 at 17:04.
    Web Hound
    $x='010000010110001101101001011001000101001001100101011010010110011101101110';
    for($i=0;$i<strlen($x);$i+=8)print(chr(bindec(substr($x,$i,8))));

  8. #8
    PHP warrior dkode's Avatar
    Join Date
    Sep 2001
    Location
    Planet Namek
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tried that. i didnt post the code before. heres the entire script if anyone can get it to work.

    PHP Code:
    <html>
    <head><basefont face="Arial"></head>
    <body>
    <?php

    if (!$_POST['q']) {
    ?>
        <h2>Search</h2>
        <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Search term: <input type="text" name="q">
        </form>
    <?
    }
    else {
        
    // 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' => 'YOUR-GOOGLE-KEY-HERE',   // Google license key
             
    'q'   => $_POST['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)) {
    ?>
            <h2>Error</h2>
            <? echo $result['faultstring'];?>
    <?    
        
    }
        else {
    ?>
            <h2>Search Results</h2>
            <? echo $result['estimatedTotalResultsCount'] . " hits found in " $result['searchTime'] . " ms"?>
            <ul>
    <?
            
    if (is_array($result['resultElements'])) {
                foreach (
    $result['resultElements'] as $r) {
                    echo 
    "<li><a href=" $r['URL'] . ">" $r['title'] . "</a>";
                    echo 
    "<br>";
                    echo 
    $r['snippet'] . "(" $r['cachedSize'] . ")";
                    echo 
    "<p>";
                }
            }
            
    print_r($result);
    ?>
            </ul>
    <?
        
    }
    }
    ?>
    </body>
    </html>
    to signup for a google api key go to:

    Google API

  9. #9
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Notice you've used the Pear SOAP client (perhaps the articles writer didn't test it).

    Think the general problem is the SOAP client needs to convert the SOAP object into a PHP object or a set of variables PHP can handle.

  10. #10
    SitePoint Evangelist
    Join Date
    Oct 2001
    Posts
    592
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Not that I know anything about SOAP, Google or anything like that, but it seems to me that when the results are indeed returned as an object, then you should do:

    PHP Code:
    foreach ($result->resultElements as $r)
    {
        echo 
    $r->snippet;

    Anyway, just my 2 cents.

    Vincent

  11. #11
    PHP warrior dkode's Avatar
    Join Date
    Sep 2001
    Location
    Planet Namek
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Vincent!

    you were correct! thank you very much. i dont know why i didnt think of something like that earilier. I guess the stdClass Object thingy really confused me!

    thanks again!!!
    "Mankind cannot define memory, yet it defines mankind"
    -- Project 2501, Ghost in the Shell

    Smarty | PEAR | PHP Manual | MySQL Manual

  12. #12
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Anyway, just my 2 cents.

    Vincent
    Whats the exchange rate on Vincents dollar? Wanna get me some

    Nice one.

  13. #13
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    After a moments further pondering, this is interesting stuff. Turns out both SOAP and XML-RPC allow you to pass data structures which are objects.

    I'd just been getting down to thinking about how web services allow you to distribute processor load.

    For example say you get an array from a web server, you can use PHP's array functions on the client to do things like sort the array or even search the array and display the results without having to send another request to the web server.

    Haven't grasped yet what additional stuff you could do with a SOAP/XML-RPC object but the brain is ticking over.

    Seems to me that the first thing the client script should do is register what it received from the server in a session variable. Looks like this is worth reading.

    So with the Google API, may be you can manipulate the the object first, perhaps filtering out some of the search results.
    Last edited by HarryF; Jul 26, 2002 at 10:50.

  14. #14
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    vincent: heh, didnt I just say that 3 posts before? I guess it had to be said twice to be noticed.
    Web Hound
    $x='010000010110001101101001011001000101001001100101011010010110011101101110';
    for($i=0;$i<strlen($x);$i+=8)print(chr(bindec(substr($x,$i,8))));

  15. #15
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is opening up a can of worms (new to me at least).

    Vincent - may be you (or someone) can help here. The equivalent scenario, forgetting about web services for a moment, can you explain what advantages mysql_fetch_object() has over mysql_fetch_array().

    In other words what is it you can do with data returned from mysql_fetch_object that you can't with mysql_fetch_array?

  16. #16
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    HarryF: it seems to me that the only difference is the notation, -> instead of [], internally php stores both in a sort of hash table, but with the [] notation you have more flexibility over what they key name is, eg. spaces
    Web Hound
    $x='010000010110001101101001011001000101001001100101011010010110011101101110';
    for($i=0;$i<strlen($x);$i+=8)print(chr(bindec(substr($x,$i,8))));

  17. #17
    SitePoint Evangelist
    Join Date
    Oct 2001
    Posts
    592
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In addition to AcidReign's post above, I'd like to say that I never use the ..._fetch_object functions myself. The reason is that they return a 'struct' (which is a class with all public data members). I'm a great believer in full data hiding in OOP, so an object with just data members and no access methods make no sense to me.

    What I usually do is put the result array in an object, and then use access methods to get to the data. For example:

    PHP Code:
    class PersonRecord
    {
        var 
    $row;

        function 
    PersonRecord(&$row)
        {
            
    $this->row =& $row;
        }

        function 
    getName()
        {
            return 
    $this->row['name'];
        }

    This way, I achieve full encapsulation, the advantages of which I'm not going to explain here (I think I already did that once )

    Whether I use an object or an array in the encapsulated class doesn't really matter; because I don't access it directly anyway. However I belief that arrays are less expensive than objects in PHP, so that's why I use those.

    Oh, and a small note to AcidReign on the subject of you already mentioning that the result should be accessed as an object: although you did indeed say this, you gave the wrong code to explain it. Just take a good look at the code you posted, and you'll see

    Vincent

  18. #18
    SitePoint Evangelist
    Join Date
    Oct 2001
    Posts
    592
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Oh, and another thing

    Just wanted to pointed another thing about those objects (and arrays): be aware that the 'foreach' operator is an expensive one! When you write:

    PHP Code:
    foreach ($list as $item)
    {
        
    // Do something with $item

    ...then every element of $list is COPIED to $item in turn. This can be very memory intensive if the elements are large. Also, when the array consists of a list of objects (possibly with references in them), you will almost certainly get strange, unwanted behavior.

    Using the array-specific iteration methods (see the PHP reference manual) you can traverse an array and get a reference to each element (instead of a copy), which not only saves memory, but is very likely what you really want.

    To be on the safe side of things, I only use foreach for very simple arrays (like a list of scalar values), and never with more complex things like arrays of objects, or multidimensional arrays.

    Vincent

  19. #19
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    vincent: yes I see, I had not noticed earlier, I was just trying to fix part of dkode's code.

    and I would agree that (if it's what you mean):
    PHP Code:
    for( $idx 0$idx count$result->resultElements ); $idx++ )... 
    would be alittle more efficient with resources (memory/speed) but it often makes little difference in my experience, as I use it where the elements are scalar types, rather then objects or arrays.
    Web Hound
    $x='010000010110001101101001011001000101001001100101011010010110011101101110';
    for($i=0;$i<strlen($x);$i+=8)print(chr(bindec(substr($x,$i,8))));

  20. #20
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    vincent: heh, your last sentence didnt even register in my mind untill after I submitted that post ;-)
    Web Hound
    $x='010000010110001101101001011001000101001001100101011010010110011101101110';
    for($i=0;$i<strlen($x);$i+=8)print(chr(bindec(substr($x,$i,8))));

  21. #21
    SitePoint Evangelist
    Join Date
    Oct 2001
    Posts
    592
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually, a for loop based on the total number of elements in an array isn't very efficient either. As I recall (but correct me if I'm wrong), the size of an array isn't actually stored in the array. That means that if you write 'count($array)', the array is traversed completely to find out how many elements are there. In other words, when you write:

    PHP Code:
    for ($i 0$i count($array); $i++)
    {
        
    //

    ...then you're actually traversing the array many times (n^2 times actually!). Better would be:

    PHP Code:
    $size count($array);
    for (
    $i 0$i $size$i++)
    {
        
    //

    In terms of complexity that's an O(n) algorithm, but it's still O(n*2), which in real life can be a lot slower than O(n)

    A real O(n) algorithm can be written when using the built-in array functions 'next', 'reset', 'current' and so on in some combination. (One I always forget anyway.) For easy use I wrote an ArrayIterator class a long time ago, and now I almost always do this:

    PHP Code:
    for ($it =& new ArrayIterator($array); $it->isValid(); $it->next())
    {
        
    $value =& $it->getCurrent();
        
    // ...

    Yes, it costs more because I'm instantiating an object, but on the other hand I don't have to remember those strange PHP functions. My class works for all arrays, no matter what type of data they contain, or whether they are indexed arrays or hashes. And it returns references instead of copies. Since I wrote this class, I happily forgot PHP's built-in array functions.

    Vincent

  22. #22
    SitePoint Zealot
    Join Date
    Dec 2001
    Location
    Ontario, Canada
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    actually the size of the array is stored, as all PHP's arrays are hash tables, not actual arrays the way C's arrays are, and even with C its not traversed, its calculated number of bytes devided by sizeof datatype, altho just storing the number in a variable, and checking that, is just slightly faster, there isnt much point as its only nano (aka micro) seconds.
    Web Hound
    $x='010000010110001101101001011001000101001001100101011010010110011101101110';
    for($i=0;$i<strlen($x);$i+=8)print(chr(bindec(substr($x,$i,8))));

  23. #23
    SitePoint Evangelist
    Join Date
    Oct 2001
    Posts
    592
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    AcidReigh, you're (almost) right. After reading your post I started to doubt myself again, so I looked it up (in the PHP source). In PHP arrays are stored in a special struct that not only stores the elements, but the number of elements as well.

    I guess that's what you get when you make assumptions and don't check them

    Oh, and remind me to not look at the PHP source again. I'm glad it all works, but considering how it looks, it's a real miracle...

    Vincent

  24. #24
    Grumpy Mole Man Skunk's Avatar
    Join Date
    Jan 2001
    Location
    Lawrence, Kansas
    Posts
    2,067
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As a general rule for all of my C-style pprogramming (including PHP and Java) I use the following construct whenever I want to loop through an array via its index:
    Code:
    for ($i = 0, $j = count($array); $i < $j; $i++) {
      // ...
    }
    That has huge performance advantages in some C and doesn't lead to any disadvantages in other languages so I do it wverywhere as a matter of habit

  25. #25
    PHP warrior dkode's Avatar
    Join Date
    Sep 2001
    Location
    Planet Namek
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    wow,

    looks like the topic went way off, but it's kind of interesting where the conversation went. I never really thought of performance advantages of array traversing that much. oh well..i will next time
    "Mankind cannot define memory, yet it defines mankind"
    -- Project 2501, Ghost in the Shell

    Smarty | PEAR | PHP Manual | MySQL Manual


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •