orvice / google-custom-search-api
此包最新版本(dev-master)没有提供许可信息。
Google Custom Search api
dev-master
2016-04-15 14:47 UTC
Requires (Dev)
- phpunit/phpunit: ~5.0
This package is not auto-updated.
Last update: 2024-09-26 00:05:46 UTC
README
本项目旨在创建一个结构良好的PHP库,用于访问通过Google APIs console提供的Google API。
目前该库允许您与以下Google API进行程序交互:
- Google Custom Search API v1
- Google Translate API v2 (自2011年12月1日起仅限付费服务)
- (更多功能即将推出)
要求
- 该库仅支持PHP 5.3.0及以上版本。
- 假设存在自动加载器。如果您需要,可以在此处找到。
- 每个API都需要一个API密钥,您可以从Google APIs console获取。
安装
只需下载库并将src
文件夹添加到您的项目中。
使用方法
注意:更详细的文档将在稍后提供。
自定义搜索API
注意:除了API密钥外,Google Custom Search API v1还需要一个Google Custom Search ID或指定URL。
以下是一个简单的Google Custom Search API v1请求示例:
$apiClient = new \Google\Api\CustomSearch();
$apiClient->setApiKey('INSERT_YOUR_API_KEY_HERE');
$apiClient->setCustomSearchEngineId('INSERT_YOUR_CUSTOM_SEARCH_ENGINE_ID_HERE');
$apiClient->setQuery('flowers');
$response = $apiClient->executeRequest();
要从$response
获取结果,
if ($response->isSuccess())
{
foreach($response->getData()->getItems() as $item)
{
echo $item->getHtmlTitle(), ' - <a href="', $item->getLink(), '">', $item->getDisplayLink(), '</a><br />';
}
}
翻译API
以下是一个简单的Google Translate API v2请求示例:
$apiClient = new \Google\Api\Translate();
$apiClient->setApiKey('INSERT_YOUR_API_KEY_HERE');
$apiClient->addSourceText('The quick brown fox jumps over the lazy dog.');
$apiClient->setTargetLanguage('fr');
$response = $apiClient->executeRequest();
要从$response
获取翻译,
if ($response->isSuccess())
{
foreach($response->getData()->getTranslations() as $translation)
{
echo $translation->getTranslatedText(), '<br />';
}
}
测试
要运行测试,请确保您已安装PHPUnit 3.6.0或更高版本,并在项目根目录中运行以下命令:
phpunit