eth*_*hmz 4 php curl google-places-api
我正在尝试使用curl从Google Place照片中抓取照片并将其保存在我的服务器上.
根据Google API文档的请求格式如下:
https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CoQBegAAAFg5U0y-iQEtUVMfqw4KpXYe60QwJC-wl59NZlcaxSQZNgAhGrjmUKD2NkXatfQF1QRap-PQCx3kMfsKQCcxtkZqQ&sensor=true&key=AddYourOwnKeyHere
Run Code Online (Sandbox Code Playgroud)
所以我尝试了这个功能:
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");
Run Code Online (Sandbox Code Playgroud)
..where $photo
持有请求网址.
这不起作用,它保存带有标题错误的空图像,这可能是因为请求不是照片的实际网址.此外,在请求网址中,我不可能知道我将获得哪个图像扩展(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;
}
Run Code Online (Sandbox Code Playgroud)
因此,您将Google Place Photo请求uRL传递给此函数,它会在重定向后返回照片的实际网址,然后可以与CURL一起使用.它还解释了有时,卷曲选项curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
并不总是有效.
归档时间: |
|
查看次数: |
1864 次 |
最近记录: |