翼度科技»论坛 编程开发 PHP 查看内容

PHP和Composer做语法转换工具

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
原文地址:https://www.mengze2.cn/post/5/
最近不是把博客的一些文章从和HTML转到Markdown了吗,因为之前换到了wordpress所以是HTML,但是这些文章再typecho无法被解析,于是就打算开发一个Markdown2HTML工具
下面使我的开发笔记,可能比较含糊
项目结构

一般情况下,我不会这么干,但是为了文章,还是需要定义的项目结构:
  1. markdown2html/
  2. ├── index.php
  3. ├── convert.php
  4. ├── styles/
  5. │   └── bootstrap.min.css
  6. └── js/
  7.     └── bootstrap.bundle.min.js
复制代码


  • index.php: 前端页面,包含输入框和按钮。
  • convert.php: 后端逻辑处理,将HTML转换为Markdown或将Markdown转换为HTML。
  • styles/: 存放CSS文件。
  • js/: 存放JavaScript文件。
准备工作

下载Bootstrap

Bootstrap官方网站下载最新版本的Bootstrap,并将bootstrap.min.css放入styles/文件夹,将bootstrap.bundle.min.js放入js/文件夹。也就是所谓的按需导入
编写前端页面 (index.php)

编写前端页面,包含一个文本输入框和两个按钮,分别用于将HTML转换为Markdown和将Markdown转换为HTML。这里不要求好看,而且需要快速开发响应式页面,所以选择bootstrap
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>转换工具</title>
  7.     <link rel="stylesheet" href="styles/bootstrap.min.css">
  8. </head>
  9. <body>
  10.    
  11.         <h1 >转换工具</h1>
  12.         <form id="convertForm" method="post">
  13.             
  14.                 <label for="inputText" >Input Text</label>
  15.                 <textarea  id="inputText" name="inputText" rows="10"></textarea>
  16.             
  17.             
  18.                 <button type="button"  onclick="convert('html2markdown')">HTML转Markdown</button>
  19.                 <button type="button"  onclick="convert('markdown2html')">Markdown转HTML</button>
  20.             
  21.             
  22.                 <label for="outputText" >Output Text</label>
  23.                 <textarea  id="outputText" name="outputText" rows="10" readonly></textarea>
  24.             
  25.         </form>
  26.    
  27.    
  28.    
  29. </body>
  30. </html>
复制代码

编写后端逻辑 (convert.php)

接下来,编写后端逻辑,将HTML转换为Markdown或将Markdown转换为HTML。
  1. [/code][align=center][/align]
  2. [size=4]添加依赖[/size]
  3. 需要安装两个PHP库来实现转换功能:
  4. [indent]Composer是一个包管理器,类似node的npm,和我发现PHP和Vue有异曲同工之妙
  5. [/indent]
  6. [list]
  7. [*]league/html-to-markdown: 将HTML转换为Markdown。
  8. [*]michelf/php-markdown: 将Markdown转换为HTML。
  9. [/list]在项目根目录下创建一个composer.json文件,内容如下:
  10. [code]{
  11.     "require": {
  12.         "league/html-to-markdown": "^5.0",
  13.         "michelf/php-markdown": "^1.9"
  14.     }
  15. }
复制代码

然后运行composer install来安装这些依赖。
  1. composer install
复制代码
最终效果

启动本地服务器(例如使用php -S localhost:8000),访问http://localhost:8000/,就可以看到转换工具的界面了。

来源:https://www.cnblogs.com/MengZe2/p/18388644
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具