使用foreach检索谷歌图片搜索

时间:2014-08-30 11:21:09

标签: image foreach

我使用以下功能获取谷歌搜索图像

function get_images($query){
    $url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
    $url .= urlencode($query);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    //decoding request
    $result = json_decode($data, true);

    return $result;
}

使用print_r()

输出所有结果时效果很好
  $images = get_images("porsche");
    print_r($images);

但是当我想使用foreach()

获取特定值时
foreach ($images->responseData->results as $result) {
    echo $result->url;
}

我收到了一个错误:

Notice:  Trying to get property of non-object 

如何使用foreach()来获取任何特定值?

1 个答案:

答案 0 :(得分:1)

试试这个:

<?php
   function get_images($query){
    $url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
    $url .= urlencode($query);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    //decoding request
    $result = json_decode($data, true);

    return $result;
}

 $images = get_images("porsche");
    //print_r($images);

  foreach ($images['responseData']['results'] as $result) {
    echo $result['url']. "<br>";
}
?>

<强>输出

http://upload.wikimedia.org/wikipedia/commons/e/e7/2012_NAIAS_Red_Porsche_991_convertible_(world_premiere).jpg
http://www.inautonews.com/wp-content/uploads/2012/05/porsche-911-club-coupe-1.jpg
http://o.aolcdn.com/hss/storage/adam/6e58b30fb96bf0d28d10fa6d290682e7/porsche-exclusive-911t-cab.jpg
http://media.caranddriver.com/images/media/510773/porsche-960-updated-inline-photo-514518-s-original.jpg