keinos/mastodon-streaming-api-parser

解析 Mastodon Streaming API 的服务器端发送事件到 JSON。

1.0.1 2020-07-24 17:10 UTC

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]"
    }
  • 接口: ParserInterface.php

示例

// 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);

规格/信息

贡献

  • 问题
  • PR(Pull Request)
    • 请将 PR 提交给 padawan 分支。CI 测试/审查后,将合并到 master 分支。
    • 更多信息请参阅: CONTRIBUTE.md
  • 规则
    • 友好,快乐,安全。