用 Laravel 生成 JSON Feed(献给站长)
这篇文章的内容应用范围不是很广,但是只是了解 Feed 是一个什么东西的话,还是可以看看的。
JSON Feed 是一种新的基于 RSS feed 标准的 JSON 格式,通过去掉 XML 标准来简化 feed 的创建。给你的网站创建这种 Feed 很简单,它的 格式规范 写得也是相当优雅。
简单又简洁:
{
"version": "https://jsonfeed.org/version/1",
"title": "My Example Feed",
"home_page_url": "https://example.org/",
"feed_url": "https://example.org/feed.json",
"items": [
{
"id": "2",
"content_text": "This is a second item.",
"url": "https://example.org/second-item"
},
{
"id": "1",
"content_html": "<p>Hello, world!</p>",
"url": "https://example.org/initial-post"
}
]
}
接下来用一个简单的例子来设计一个这样的 Feed。
获取帖子列表
第一步是从数据库中获取记录列表。假设这个网站最新的一些项目是存在「Posts」表中,那我们先使用 Eloquent 去获取最新的 20 条记录:
$posts = Post::limit(20)->get();
设置主要的 JSON Feed 数据
JSON Feed 规范有几个可选的顶级字段,如标题、Feed URL、站点图标等。由于这些都不是动态的,我们得手动把它们添加到数组中:
$data = [
'version' => 'https://jsonfeed.org/version/1',
'title' => 'Example Feed',
'home_page_url' => 'https://example.org/',
'feed_url' => 'https://example.org/feed/json',
'icon' => 'https://example.org/xxxxx.png',
'favicon' => 'https://example.org/xxxxxx.png',
'items' => [],
];
这上面为空的 items
是用来保存我们拿下来的最新的帖子。
添加 JSON Feed 的 Items
最后一步是循环遍历第一步中拿下来的 $posts
,并将其添加到 items
数组中。像这样:
foreach ($posts as $key => $post) {
$data['items'][$key] = [
'id' => $post->id,
'title' => $post->title,
'url' => 'https://example.org/'.$post->uri,
'image' => $post->featured_image,
'content_html' => $post->parsed_content,
'date_published' => $post->created_at->tz('UTC')->toRfc3339String(),
'date_modified' => $post->updated_at->tz('UTC')->toRfc3339String(),
'author' => [
'name' => $post->user->name
],
];
}
这上面唯一需要特别定制的是时间戳。上面利用了 Carbon 转换为 UTC,然后再转换为 JSON 规范要求的 RFC 3339 格式。
最终结果
下面是懒人专用的方法完整版:
public function json()
{
$posts = Post::active()->limit(20)->get();
$data = [
'version' => 'https://jsonfeed.org/version/1',
'title' => 'Example Feed',
'home_page_url' => 'https://example.org/',
'feed_url' => 'https://example.org/feed/json',
'icon' => 'https://example.org/xxxxx.png',
'favicon' => 'https://example.org/xxxxx.png',
'items' => [],
];
foreach ($posts as $key => $post) {
$data['items'][$key] = [
'id' => $post->id,
'title' => $post->title,
'url' => 'https://example.org/'.$post->uri,
'image' => $post->featured_image,
'content_html' => $post->parsed_content,
'date_created' => $post->publishes_at->tz('UTC')->toRfc3339String(),
'date_modified' => $post->updated_at->tz('UTC')->toRfc3339String(),
'author' => [
'name' => $post->user->name
],
];
}
return $data;
}
这里只需返回 $data
数组,它会自动转换为 JSON 格式。关于这件事情, Mateus Guimarães 还为此写了个 扩展包~
犹豫着要不要翻译因为感觉这玩意只有站长会用到~
嘛,就献给所有使用 Laravel 开发的站长吧 :rose:
本作品采用《CC 协议》,转载必须注明作者和本文链接
赞一个。
这个JsonFeed composer 包的话 JsonFeed::setItems($data)->toJson() 会直接报错,不知道怎么回事 包都引用好了
直接use的话就直接 Non-static method Mateusjatenee\JsonFeed\JsonFeed::setItems()