我尝试使用curl从Google Place照片中抓取照片并将其保存在我的服务器上。
根据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
包含请求网址。
这不起作用,它会保存带有标题错误的空图像,这可能是因为请求不是照片的实际网址。此外,在请求网址中,我们无法知道我将获得哪个图片扩展程序(jpg,png,gif等),这是另一个问题。
有关如何保存照片的任何帮助。
编辑:我收到标题错误"无法读取文件标题"在我尝试打开图像时,在我的图像查看器软件中。脚本本身并没有显示任何错误。
答案 0 :(得分:5)
我在这里找到了一个解决方案: 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请求uRL传递给此功能,并在重定向后返回照片的实际网址,然后可以与CURL一起使用。它还解释了有时候,卷曲选项curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
并不总是有效。