引言
准备工作
在开始之前,请确保你的环境中已经安装了PHP和GD库。GD库是PHP处理图像的一个扩展库,它允许你创建、编辑和处理图像。
使用Google API进行图片搜索
1. 获取API密钥
首先,你需要到Google Cloud Console创建一个项目,并启用Google Custom Search API。在API & Services > Credentials中,创建一个新的API密钥。
2. 配置API密钥
在你的PHP代码中,需要设置以下参数:
$api_key = '你的API密钥';
$cx = '你的自定义搜索ID';
3. 发起搜索请求
function searchImages($query) {
$url = "https://www.googleapis.com/customsearch/v1?q=" . urlencode($query) . "&key=" . $api_key . "&cx=" . $cx . "&searchType=image";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$query = '猫咪';
$results = searchImages($query);
4. 处理搜索结果
foreach ($results['items'] as $item) {
echo '<img src="' . $item['link'] . '" alt="' . $item['title'] . '" />';
}
使用Bing API进行图片搜索
1. 获取API密钥
在Bing Search API的官方网站上创建一个应用,并获取API密钥。
2. 配置API密钥
在你的PHP代码中,设置以下参数:
$api_key = '你的API密钥';
3. 发起搜索请求
function searchImagesBing($query) {
$url = "https://api.bing.microsoft.com/v7.0/images/search?q=" . urlencode($query) . "&count=10&key=" . $api_key;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$query = '狗狗';
$results = searchImagesBing($query);
4. 处理搜索结果
foreach ($results['value'] as $item) {
echo '<img src="' . $item['contentUrl'] . '" alt="' . $item['name'] . '" />';
}