intellexapps / pixabay-api-client
Pixabay API 的轻量级 PHP 客户端
v1.0.1
2023-12-17 02:22 UTC
Requires
- php: >=7.4
- ext-curl: *
- ext-json: *
Requires (Dev)
- phpstan/phpstan: *
- phpunit/phpunit: ^9.6
- squizlabs/php_codesniffer: ^3.8
This package is auto-updated.
Last update: 2024-09-17 04:00:14 UTC
README
- 支持完整的 Pixabay API
- 包括 图片 和 视频
- 使用 严格类型流畅设置器 定义搜索参数
- 用于 下载 结果的实用工具类
- 未使用任何 第三方 库
免责声明
在开发过程中,API 发生了一些小的变化:他们从响应中移除了“收藏”计数。然而,这破坏了我们的代码,使得 v1.x.x 无法使用。
请注意:Pixabay 方面的任何更改 都可能导致 该库在任何时候无法使用。有关更多信息,请参阅 许可。
使用方法
以下是从 tests/examples 目录中的文件片段。
视频
// Invoke the API directly by passing an array for the search $response = (new VideoApi(API_KEY))->fetch(new VideoSearchParams([ 'category' => Category::TRANSPORTATION, 'editors_choice' => true, 'per_page' => 3 ])); // Show images foreach ($response->getVideos() as $video) { echo $video->getMediumVideo()->getUrl() . PHP_EOL; }
图片
// Define search parameters using fluent setters $search = (new ImageSearchParams()) ->setColors([ Color::GREEN, Color::ORANGE ]) ->setImageType(ImageType::PHOTO) ->setCategory(Category::NATURE) ->setEditorsChoice(true) ->setPerPage(3); // Invoke the API $response = (new ImageApi(API_KEY))->fetch($search); // Show images foreach ($response->getImages() as $image) { echo $image->getURLForSize180() . PHP_EOL; }
下载结果
// Destination must be defined if ($argc < 2) { echo "Usage: php -f tests/examples/download.php <destination> <count>"; exit(1); } // Read the input parameters $count = (int) min(50, $argv[2] ?? 50); $destination = rtrim($argv[1], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; if (!is_dir($destination) || !is_writable($destination)) { echo "Supplied destination is not a writable directory: ${destination}"; exit(2); } // Invoke the API $response = (new ImageApi(API_KEY))->fetch(new ImageSearchParams([ PixabayParam::Q => 'kitten', PixabayParam::CATEGORY => Category::ANIMALS, PixabayParam::IMAGE_TYPE => ImageType::PHOTO, PixabayParam::ORIENTATION => Orientation::HORIZONTAL, PixabayParam::PER_PAGE => $count, PixabayParam::SAFE_SEARCH => true, PixabayParam::EDITORS_CHOICE => true, PixabayParam::ORDER => OrderAlias::POPULAR ])); // Download and store $images = $response->getImages(); $count = count($images); foreach ($images as $i => $image) { $preview = explode('/', $image->getPreviewURL()); $name = end($preview) . PHP_EOL; echo sprintf("%3s / %3s, %s", $i + 1, $count, $name); Downloader::downloadTo($image->getLargeImageURL(), "{$destination}/{$name}"); }
运行示例
为了运行示例,需要定义 Pixabay API 密钥。
PIXABAY_API_KEY=0000000-0000000000000000000000000 php -f tests/examples/images.php
PIXABAY_API_KEY=0000000-0000000000000000000000000 php -f tests/examples/videos.php
PIXABAY_API_KEY=0000000-0000000000000000000000000 php -f tests/examples/download.php ~/Desktop/ 5
参考
致谢
脚本由 Intellex 团队编写。