使用 PHP 以 HTML 格式返回 Google 图片搜索结果 [英] Return Google Image Search Results in HTML using PHP
问题描述
我知道如何使用 Google API 在 AJAX 中返回图像结果,但我希望能够为特定查询返回图像,然后将它们输出到我页面上的 HTML 中.
I know how we can use the Google API to return image results in AJAX, but I want to be able to return images for a specific query and then output them in to HTML on my page.
例如:
http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=sausages
返回带有关键字 sausages 前 10 个结果的信息和图像的结果.
Returns results with infomation and images about the top 10 results for the keyword sausages.
如何在 HTML 中使用 PHP 查询此 url 以输出我页面上图像的图像和标题.
How can I query this url to output the images and titles of the images on my page using PHP in HTML.
我在函数顶部使用以下内容返回标题:
I am using the following at the top of the function to return the title:
$tit = get_the_title();
然后我在这里附加它:
$json = get_url_contents('http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q='.$tit.'');
但它不会识别标题
推荐答案
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;
}
$json = get_url_contents('http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=sausages');
$data = json_decode($json);
foreach ($data->responseData->results as $result) {
$results[] = array('url' => $result->url, 'alt' => $result->title);
}
print_r($results);
输出:
Array
(
[0] => Array
(
[url] => http://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/Salchicha_oaxaque%25C3%25B1a.png/220px-Salchicha_oaxaque%25C3%25B1a.png
[alt] => Sausage - Wikipedia, the free encyclopedia
)
[1] => Array
(
[url] => http://upload.wikimedia.org/wikipedia/commons/c/c1/Reunion_sausages_dsc07796.jpg
[alt] => File:Reunion sausages dsc07796.jpg - Wikimedia Commons
)
[2] => Array
(
[url] => http://1.bp.blogspot.com/-zDyoLPoM1Zg/ULXDPba_2iI/AAAAAAAAAAs/QzfNNmDFmzc/s1600/shop_sausages.jpg
[alt] => Maik's Yummy German Sausage
)
[3] => Array
(
[url] => http://sparseuropeansausage.com/images/sausage-web/sausagesBiggrilling2.jpg
[alt] => Spar's European Sausage Shop
)
)
显示图像:
<?php foreach($results as $image): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>"/><br/>
<?php endforeach; ?>
<小时>
评论后
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' . get_the_title();
$json = get_url_contents($url);
这篇关于使用 PHP 以 HTML 格式返回 Google 图片搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!