如何導入#
xLog 可以直接導入markdown
檔案並支援front matter
,所以只需要從資料庫中導出文章並設定為hexo
格式即可。
導入過程#
直接使用 php 的Pdo
將資料庫中的typecho_contents
表導出為檔案即可,程式碼如下,可根據實際情況微調。
<?php
// 連接到資料庫
$dsn = 'mysql:host=localhost;dbname=blog;charset=utf8';
$username = 'root';
$password = '123456';
$conn = new PDO($dsn, $username, $password);
// 設定錯誤處理
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 執行查詢
$sql = 'SELECT * FROM `typecho_contents` WHERE `type` = "post"';
$stmt = $conn->prepare($sql);
$stmt->execute();
// 遍歷結果集
$results = $stmt->fetchAll();
foreach ($results as $result) {
// 輸出資料
echo $result['title'] . "\n\n";
// 獲取標籤與文章關聯關係
$s_sql = 'SELECT * FROM `typecho_relationships` WHERE `cid`=' . $result['cid'];
$stmt2 = $conn->prepare($s_sql);
$stmt2->execute();
$relationships = [];
foreach($stmt2->fetchAll() as $s){
$relationships[] = $s['mid'];
}
// 獲取標籤名稱
$t_sql = 'SELECT `name` FROM `typecho_metas` WHERE `mid` in (\''. implode("','", $relationships) .'\') and `type`=\'\'';
$stmt3 = $conn->prepare($t_sql);
$stmt3->execute();
$tags = [];
foreach($stmt3->fetchAll() as $t){
$tags[] = $t['name'];
}
// 生成 Markdown 檔案
$str = '---
tags:
- '. implode("\n - ", $tags) .'
type: note
title: "' . $result['title'] . '"
date: ' . date('Y-m-d H:i:s', $result['created']) . '
updated: ' . date('Y-m-d H:i:s', $result['modified']) . '
---
';
file_put_contents(__DIR__ . '/blog/' . str_replace('/', '_', $result['title']) . '.md', str_replace('<!--markdown-->', $str, $result['text']));
}
// 關閉連接
$conn = null;
檔案會存在當前目錄下的blog
資料夾 (若無需自行建立,因為我懶得沒寫mkdir
)
一些問題#
目前存在以下問題尚待解決。
- 導出的 md 檔案
標籤
以及最後修改時間
不生效 - 導入
xLog
後無法修改標籤 (應該是xLog
的 bug) - 圖片無法自動上傳到
IPFS
上
最後一點是讓我最難受的,所以又把上傳的文章刪掉了,等我找到解決辦法再遷移。