gfargo / newsapi
NewsAPI.org 的 PHP API 包装器
0.2.0
2019-01-25 02:35 UTC
Requires
- php: >=7.1
- rmccue/requests: ^1.7
Requires (Dev)
- phpunit/phpunit: 7.5
- squizlabs/php_codesniffer: 3.*
This package is auto-updated.
Last update: 2024-09-29 05:02:24 UTC
README
🗞 PHP 包装器 for NewsAPI.org
入门
在您的 PHP 应用程序中实现 NewsAPI 从未如此顺利。其设计原则是简单,不牺牲力量或灵活性。
安装
通过 Composer 将其添加到您的项目中。
composer require gfargo/newsapi
依赖项
此包装器使用了 Ryan McCue 的 Requests 库。
官方网站和文档可以在 这里 找到。
配置
一旦包含在您的项目中,设置应该非常简单。唯一要求是来自 NewsAPI.org 的有效 API 密钥。
用法
步骤 1. 设置访问令牌
\NewsAPI\Client::setAccessToken('276537c6a3824cdd9eae393c024ff732');
步骤 2. 设置查询
通过 query
方法向 API 发送请求,该方法接受三个参数。下面是一些示例。
查询参数
(string) $endpoint
目标端点。选项有top
、everything
和sources
。(array) $query_params
传递给 NewsAPI.org 的查询参数(array) $request_options
传递给 Requests 库以控制 CURL 的选项
示例
// All articles featuring the keyword 'Open Source' $request = NewsAPI\Client::query( 'everything', [ 'q' => 'Open Source' ] );
// Top headlines for articles featuring the keyword 'Technology' $request = NewsAPI\Client::query( 'top', [ 'q' => 'Technology' ] );
// Top articles from 'Business' category $request = NewsAPI\Client::query( 'top', [ 'category' => 'business' ] );
步骤 3. 处理响应
每个查询都返回一个 Request_Response
对象,更多关于此 这里。
简而言之,Requests
库使得处理 API 响应变得容易。
$request = NewsAPI\Client::query( 'top', [ 'category' => 'business' ] ); $request->status_code // int(200) $request->headers['content-type'] // string(31) "application/json; charset=utf-8" $request->url // string(54) "https://newsapi.org/v2/top-headlines?category=business" $request->body // string(14385) "{...}"