php - 使用 curl 从 Google Places API Place Photos 保存照片副本

标签 php curl google-places-api

我正在尝试使用 curl 从 Google Place Photos 抓取照片并将其保存在我的服务器上。

请求格式符合 Google API documentation是这样的:

https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CoQBegAAAFg5U0y-iQEtUVMfqw4KpXYe60QwJC-wl59NZlcaxSQZNgAhGrjmUKD2NkXatfQF1QRap-PQCx3kMfsKQCcxtkZqQ&sensor=true&key=AddYourOwnKeyHere

所以我尝试了这个功能:

function download_image1($image_url, $image_file){
    $fp = fopen ($image_file, 'w+');
    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FILE, $fp); // output to file
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000); // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    // curl_setopt($ch, CURLOPT_VERBOSE, true); // Enable this line to see debug prints
    curl_exec($ch);
    curl_close($ch); // closing curl handle
    fclose($fp); // closing file handle
}

download_image1($photo, "test.jpg");

..其中 $photo 包含请求 url。

这是行不通的,它保存了一个带有标题错误的空图像,这可能是因为请求不是照片的实际 url。此外,在请求 url 中,不可能知道我将获得哪个图像扩展名(jpg、png、gif 等),所以这是另一个问题。

感谢任何有关如何保存照片的帮助。

编辑:当我尝试打开图像时,我在图像查看器软件中收到标题错误“无法读取文件标题”。脚本本身没有显示任何错误。

最佳答案

我在这里找到了解决方案: http://kyleyu.com/?q=node/356

它提供了一个非常有用的函数来在重定向后返回实际的 URL:

function get_furl($url)
    {
    $furl = false;
    // First check response headers
    $headers = get_headers($url);
    // Test for 301 or 302
    if(preg_match('/^HTTP\/\d\.\d\s+(301|302)/',$headers[0]))
        {
        foreach($headers as $value)
            {
            if(substr(strtolower($value), 0, 9) == "location:")
                {
                $furl = trim(substr($value, 9, strlen($value)));
                }
            }
        }
    // Set final URL
    $furl = ($furl) ? $furl : $url;
    return $furl;
    }

因此,您将 Google Place Photo 请求 uURL 传递给此函数,它会在重定向后返回照片的实际 URL,然后可以将其与 CURL 一起使用。它还解释了有时 curl 选项 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 并不总是有效。

关于php - 使用 curl 从 Google Places API Place Photos 保存照片副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23519103/

相关文章:

php - OOP登录/注册系统

php - 从 PHPMYADMIN 导出和导入数据

php - 400 - Curl 中的错误请求

android - URL 类呈现 - Invalid_Request with next_page_token

Android Google Place API 错误状态{statusCode=PLACES_API_ACCESS_NOT_CONFIGURED,resolution=null}

php - Google 地方信息和 cURL

PHP & MySQL striplashes() 问题

PHPdoc - 为 stdClass 对象定义对象属性

unix - Red Hat 上的 CuRL SSL 握手问题

php - Whatsapp Business Cloud API 在尝试下载媒体时返回空字符串