写博客其实已经好久了,但一直没找到舒服的写博方式,今天在转CSDN,看到CSDN的博客也可以用MARKDOWN下了,瞬间想要把以前的博客转过来的冲动,所以就花了些时间写了个程序自动搬迁了,程序很简单,只是为了记录下来,日后还会搬迁一些其他的博客内容不是?
解决方案:
先看下目录结构
HTTRequest.php 用于网络数据请求、抓取等的封装类(做过模拟请求的应该都知道)
CSDN.php 用于自动发布 csdn markdown 博客
demo.php 执行程序,可在 cli 下执行 php demo.php 测试(这里以 gitblog 的博客为例)
接下来看 CSDN.php
<?php
class csdn
{
public function publish($data, $type = 'original')
{
$uri = '/mdeditor/setArticle';// 发布博客的URI
$data['type'] = $type;// 类型,原创(original),转载,翻译
$data['status'] = 0;
$data['level'] = 0;
$data['channel'] = 17;
$data['type'] = 'original';
$data['articleedittype'] = 1;
return $this->request($uri, $data);
}
private function request($uri, $data = null)
{
$httpRequest = new HTTPRequest('write.blog.csdn.net');
$httpRequest->setRequestUri($uri);
if($data) {
$httpRequest->setType('POST');
$httpRequest->setData($data);
}
$httpRequest->setHeader('Referer', 'http://write.blog.csdn.net/mdeditor');
$httpRequest->setHeader('cookie', '这里保证是你自己的博客COOKIE');
$httpRequest->execute();
return $httpRequest->getResponseText();
}
}
调用方式
include_once('HTTPRequest.php'); include_once('csdn.php'); $csdn = new csdn; $post['title'] = urlencode('this is title'); $post['markdowncontent'] = urlencode('this is markdowncontent'); $post['content'] = urlencode('this is content'); $post['tags'] = urlencode('this is tags'); $post['description'] = urlencode('this is description'); $post['categories'] = urlencode('this is categories'); $result = $csdn->publish($post);
然后就可以根据 result 来判断是否发布成功了,比如如下方式
$result = json_decode($csdn->publish($post), 1);
if($result['status'] == 'success') {
echo 'publish success' . PHP_EOL;
} else {
echo 'publish failed' . PHP_EOL;
file_put_contents('log.txt', $val, FILE_APPEND);
}