Question

NON-WORKING Code:
Notice: Trying to get property of non-object

$i = 1;
var_dump($rez->responseData->results[$i]->url);

Fatal error: Cannot use object of type stdClass as array in

$rez = (array) $rez;
var_dump($rez['responseData']['results']['1']['url']);


RESULTS of WORKING Code:
How do I extact only urls and turn url list into an array?

stdClass Object
(
[responseData] => stdClass Object
    (
        [results] => Array
            (
                [0] => stdClass Object
                    (
                        [GsearchResultClass] => GwebSearch
                        [unescapedUrl] => http://www.rottentomatoes.com/top/
                        [url] => http://www.rottentomatoes.com/top/
                        [visibleUrl] => www.rottentomatoes.com
...........................................................................

WORKING Code:

function google_search_api($args, $referer = 'http://localhost/test/', $endpoint = 'web'){
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint;

if ( !array_key_exists('v', $args) )
    $args['v'] = '1.0';

$url .= '?'.http_build_query($args, '', '&');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// note that the referer *must* be set
curl_setopt($ch, CURLOPT_REFERER, $referer);
$body = curl_exec($ch);
curl_close($ch);
//decode and return the response
return json_decode($body);
}

$rez = google_search_api(array(
    'q' => 'movie list', 'start' => '5',
 ));

echo '<pre>';
print_r($rez);
echo '</pre>';
?>

I have tried multiple variations of the above but just am not figuring it out. Probably something simple so any comment would be appreciated.

Was it helpful?

Solution

Seems like this should work

$urls = array_map(function($result) {
    return $result->url;
}, $rez->responseData->results);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top