使用PHP展示最近一条Memos

默认分类
53 0

适用于memos v0.22.0版本

<?php
// 获取远程 API 数据
$bbUrl = "https://memos.ee/api/v1/memos?filter=visibilities==['PUBLIC']&pageSize=1";
$response = file_get_contents($bbUrl);

if ($response === false) {
    die("Failed to fetch data from API.");
}

// 解析 JSON 数据
$data = json_decode($response, true);

if (!isset($data['memos']) || empty($data['memos'])) {
    die("No memos found.");
}

// 生成 HTML
$result = '';
foreach ($data['memos'] as $memo) {
    $bbTime = $memo['createTime'];
    $bbCont = $memo['content'];

    // 替换图片和链接
    $newbbCont = preg_replace('/\!\[.*?\]\((.*?)\)/', ' <a href="$1" target="_blank">🌅</a> ', $bbCont);
    $newbbCont = preg_replace('/\[(.*?)\]\((.*?)\)/', ' <a href="$2" target="_blank">$1 🔗</a> ', $newbbCont);

    // 截取内容长度为 30 个字符
    //$newbbCont = mb_substr($newbbCont, 0, 25, 'UTF-8');

    // 计算相对时间
    $timestamp = strtotime($bbTime);
    $relativeTime = time_elapsed_string($timestamp);

    $result .= "<span class=\"datetime\">$relativeTime</span>: <a href=\"/times/\">$newbbCont</a>";
}

$bbBefore = '<div class="talk-wrap"><ul class="talk-list">';
$bbAfter = '</ul></div>';
$resultAll = $bbBefore . $result . $bbAfter;

// 输出 HTML
echo $resultAll;

// 计算相对时间的函数
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime('@' . $datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => '年',
        'm' => '个月',
        'w' => '周',
        'd' => '天',
        'h' => '小时',
        'i' => '分钟',
        's' => '秒',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . $v;
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . '前' : '刚刚';
}
?>
最后更新 2024-12-06
评论 ( 0 )
OωO
隐私评论