AI摘要:文章介绍了如何使用PHP从Mastodon API获取数据并保存为本地JSON文件。通过设置用户ID和实例地址,使用cURL请求API,循环获取最多1000条非转发的状态数据,并将其保存为toot.json文件。该方法解决了Cloudflare Workers获取API数据较慢的问题,并通过计划任务定时更新数据。
[article id="1643"]
根据 Cloudflare Workers 获取API 拉取的时候有些慢,所以使用php 获取到json 数据并保存在本地,通过计划任务定时生成.
<?php
$userId = '110711427149362311'; //改为自己的
$instance = 'jiong.us'; //改为自己的
$baseUrl = 'https://' . $instance . '/api/v1/accounts/' . $userId . '/statuses';
$limit = 20; // Maximum limit per page
$toots = [];
for ($i = 0; $i < 25; $i++) { // 25 pages * 40 toots per page = 1000 toots
$ch = curl_init();
$url = $baseUrl . '?limit=' . $limit;
if (isset($lastId)) {
$url .= '&max_id=' . $lastId;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, [
// 'Authorization: Bearer ' . $accessToken
//]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (empty($data)) {
break;
}
foreach ($data as $toot) {
if (!isset($toot['reblog']) && !isset($toot['in_reply_to_id'])) {
$toots[] = $toot;
}
}
$lastId = end($data)['id'];
}
// Now $toots contains up to 1000 toots
$jsonData = json_encode($toots, JSON_PRETTY_PRINT);
file_put_contents('toot.json', $jsonData);
?>
保存为toot.php, 访问 toot.php
则会在同级目录生成 toot.json
.
创建一个定时任务定时访问toot.php