php实现博客园xml备份数据导入到mysql数据库

 代码:

public function xml2db()
    {
        $bool = false;
        $xml = file_get_contents(env('root_path') . 'data/bk202001.xml');
        $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
//        $xmlFile = env('root_path') . 'data/bk202001.xml';
//        $obj = simplexml_load_file($xmlFile, 'SimpleXMLElement', LIBXML_NOCDATA); //数据过多会报错
        $result = (array)$obj;
        if (isset($result['channel'])) {
            $channel = (array)$result['channel'];
            if (isset($channel['item'])) {
                $items = (array)$channel['item'];
                $data = [];
                foreach ($items as $item) {
                    if (is_object($item)) {
                        $item = (array)$item;
                        $data[] = [
                            'title' => $item['title'],
                            'link' => $item['link'],
                            'author' => $item['author'],
                            'pub_date' => strtotime($item['pubDate']),
                            'description' => addslashes($item['description'])//富文本处理 预定义字符(单引号(')、双引号(")、反斜线(\)与 NUL)前添加反斜杠
                        ];
                    }
                }
                $n = $this->articleModel->storeAll($data);
                echo '共插入' . $n . '片文章';
                $bool = true;
            }
            if (!$bool) {
                echo '没有解析到数据';
            }
        }
    }

也可以借助league/html-to-markdown导出为mk

composer require league/html-to-markdown
posted @ 2020-01-11 14:50  白開水  阅读(242)  评论(0编辑  收藏  举报