使用Google Images API和CURL检索图像时,始终获得相同的链接

尼斯罗

我正在尝试使用Google的API和PHP获得许多不同的图像。该代码适用于单个图像,但是当我尝试在FOR-LOOP中使用相同的代码获取不同的主题图像时,我始终只会得到第一个结果

$images = array("ironman poster", "superman returns poster", "the croods poster", "batman forever poster");

foreach ($images as $i) {
    $image = rawurlencode($i);
    $query = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$image."&imgsz=large&as_filetype=jpg";

    $json = get_url_contents($query);
    $data = json_decode($json);
    foreach ($data->responseData->results as $result) {
        $results[] = array("url" => $result->url, "alt" => $result->title);
    }

    echo $results[0]['url'];
    echo "<br />";
    echo $query;
    echo "<br />";
}

function get_url_contents($url) {
    $crl = curl_init();
    curl_setopt($crl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
    curl_setopt($crl, CURLOPT_URL, $url);
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 5);

    $ret = curl_exec($crl);
    curl_close($crl);
    return $ret;
}
布兰登

您需要$results在循环迭代之前定义数组。我实际上不确定为什么它不起作用,也许其他人可以详细说明?

工作解决方案:

$ images = array(“钢铁侠海报”,“超人归来海报”,“ croods海报”,“蝙蝠侠永远海报”);

foreach ($images as $i) {
    $image = rawurlencode($i);
    $query = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$image."&imgsz=large&as_filetype=jpg";

    $json = get_url_contents($query);
    $data = json_decode($json);
    $results = array(); //define array here!
    foreach ($data->responseData->results as $result) {
        $results[] = array("url" => $result->url, "alt" => $result->title);
    }

    echo $results[0]['url'];
    echo "<br />";
    echo $query;
    echo "<br />";
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Google-Images API与Discord.js的集成

Google Images API的execute_transforms()返回“出现错误”

使用Python在Yandex Images中反向搜索图像

如何使用Google YouTube API检索和显示第一个结果链接?

使用Google Sheets API检索单元格中的图像

使用 BeautifulSoup 检索图像链接

如何使用Google API从onConnected()方法检索经度和纬度

Google停止使用Google Calendar API创建活动时创建Google Meet链接

Images.xcassets AppIcon和启动图像

如何使用curl获得图像?

如何使用curl的rest api从Nexus检索工件校验和?

使用 API 和 cURL 调用 Google App Script 函数

从Images.xcassets加载图像

Mapbox React Native,ShapeSource#images已弃用,请使用Images#images

使用localStorage存储和检索PNG时的空白图像

使用 Laravel9 Vue3 将图像存储在 public/images 中

启动图像未显示在iOS应用程序中(使用Images.xcassets)

google Places API使用getPlacePhotos检索照片

使用哪些Google API?

使用 Google 的路线 API

使用Google Speech API

Google Places API的使用

Google 助理 API 使用

如何从google下载图片并在google-images-download中同时使用关键字重命名图片

从Google API检索距离和行驶时间值时出错()

检索用户列表时发生Google_ServiceException错误(使用Google API SDK)

使用从Web API检索的图像URL链接在视图中显示图像

使用Google Sites API检索所有经典和新的Google网站

如何使用Node.js和Google Sheets API检索新创建的Google Sheet