keinos / mastodon-streaming-api-parser
解析 Mastodon Streaming API 的服务器端发送事件到 JSON。
1.0.1
2020-07-24 17:10 UTC
Requires
- php: ^8.0 || ^7.1
- ext-json: *
- ext-mbstring: *
Requires (Dev)
- bamarni/composer-bin-plugin: ^1.3
- phan/phan: ^2.5
- php-coveralls/php-coveralls: ^2.2
- phpbench/phpbench: @dev
- phpmd/phpmd: @stable
- phpstan/extension-installer: ^1.0
- phpstan/phpstan: ^0.12.10
- phpunit/phpunit: ^9.0 || ^8.0 || ^7.0 || ^6.5
- psalm/phar: ^3.9
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-09-25 03:05:08 UTC
README
Mastodon Streaming API 服务器端事件解析器(PHP版)
此类仅将来自 服务器端事件 的 Mastodon Streaming API 收到的行解析为 JSON 对象字符串。
以下行(服务器端事件消息)将按以下方式解析为 JSON。
5b1
event: update
data: {"id":"10000 ... visible\">0FS8QET2TT</span></a><br><a hr
350
ef=\"https://www ... ts":[],"mentions":[],"tags":[],"emojis":[]}
↓
use \KEINOS\MSTDN_TOOLS\Parser\Parser; $parser = new Parser(); while (! feof($stream)) { $line = fgets($stream); $json = $parser->parse($line); if (false === $json) { continue; } echo $json . PHP_EOL; }
↓
{"event":"update","payload":{"id":"10000 ... visible\">0FS8QET2TT<\/span><\/a><br><a href=\"https:\/\/www .... ts":[],"mentions":[],"tags":[],"emojis":[]}}
如果您直接通过套接字连接从 Mastodon Streaming API 接收流信号,而不是需要访问令牌的 WebSocket 升级协议,则使用此类。
安装
composer require keinos/mastodon-streaming-api-parser
用法
-
实例化
$parser = new \KEINOS\MSTDN_TOOLS\Parser\Parser();
-
方法
/** * @param string $line Received streaming line. * @return bool|string Returns the data unit in JSON string. Or false if the * status is "buffering in progress". */ $json = $parser->parse($line);
-
返回的 JSON 字符串结构
{ "event":"[Event name]", "payload":"[Data of the event]" }
示例
// Instantiate the parser $parser = new \KEINOS\MSTDN_TOOLS\Parser\Parser(); // Open socket $fp = fsockopen($hostname, $port, $errno, $errstr, $timeout); // Send GET request fwrite($fp, $req); // Looper while (! feof($fp)) { // Read the stream $read = fgets($fp); // Buffer each line until it returns the data $json = $parser->parse($read); if (false === $json) { continue; } // Do something with the data echo $json . PHP_EOL; } // Close connection fclose($fp);
- 完整示例请参阅: ./samples/Main.php
规格/信息
- PHP: ^7.1 || ^8.0
- 可检测的事件类型:
update和delete - 源代码: Mastodon_StreamingAPI_Parser @ GitHub
- 包发布: keinos/mastodon-streaming-api-parser @ Packagist
贡献
- 问题
- 在以下位置提出问题: https://github.com/KEINOS/Mastodon_StreamingAPI_Parser/issues
- 如果是错误,请提供可复现的简单示例。
- 如果是功能请求,请也提供希望得到的简单示例,以便我们可以在实现您的功能之前创建测试。
- PR(Pull Request)
- 请将 PR 提交给 padawan 分支。CI 测试/审查后,将合并到
master分支。 - 更多信息请参阅: CONTRIBUTE.md
- 请将 PR 提交给 padawan 分支。CI 测试/审查后,将合并到
- 规则
- 友好,快乐,安全。