我正在尝试使用Google的API和PHP获取大量不同的图片。代码适用于单个图像,但是当我尝试使用FOR - LOOP 中的相同代码获取不同主题图像时,我始终只获得第一个结果:< / p>
$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;
}
答案 0 :(得分:0)
您需要在循环迭代之前定义$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 />";
}