fastvolt/markdown
Composer 安装命令:
composer require fastvolt/markdown
包简介
A Fast, Simple and Straight-forward Markdown to HTML Converter for PHP.
README 文档
README
Markdown Parser for PHP
A fast, simple, and straightforward Markdown to HTML converter for PHP.
🚀 Installation
composer require fastvolt/markdown
📦 Basic Usage
use FastVolt\Helper\Markdown; $text = "## Hello, World"; // Initialize the parser $markdown = new Markdown(); // or Markdown::new() // set markdown content $markdown->setContent($text); // compile and get as raw HTML echo $markdown->getHtml();
Output:
<h2>Hello, World</h2>
📄 Convert Markdown File to Raw HTML
sample.md:
#### Heading 4 ### Heading 3 ## Heading 2 # Heading 1 - List 1 - List 2 > THIS IS A BLOCKQUOTE [A LINK](https://github.com/fastvolt)
index.php:
$markdown = Markdown::new(); // add markdown file to parse $markdown->addFile(__DIR__ . '/sample.md'); // compile and get as raw html echo $markdown->getHtml();
Output:
<h4>Heading 4</h4> <h3>Heading 3</h3> <h2>Heading 2</h2> <h1>Heading 1</h1> <ul> <li>List 1</li> <li>List 2</li> </ul> <blockquote><p>THIS IS A BLOCKQUOTE</p></blockquote> <a href="https://github.com/fastvolt">A LINK</a>
📝 Convert Markdown File to An HTML File
blogPost.md:
Here is a Markdown File Waiting To Be Compiled To an HTML File
index.php:
$markdown = Markdown::new() // add markdown file ->addFile(__DIR__ . '/blogPost.md') // add output directory ->addOutputDirectory(__DIR__ . '/pages/') // compile as an html file ->saveToHtmlFile(filename: 'index.html'); if ($markdown) { echo "Compiled to ./pages/index.html"; }
Convert Directory to HTML Directory Structure
This compiles all .md files in a source directory into a mirrored structure of .html files in an output directory.
use FastVolt\Helper\Markdown; use FastVolt\Helper\Markdown\Enums\MarkdownEnum; $markdown = Markdown::new() // Set the source directory to read all .md files from (including sub-directories) ->setSourceDirectory(__DIR__ . '/docs/') // Set the output directory to compile the mirrored HTML structure to (Alias: ->setCompileDir()) ->addOutputDirectory(__DIR__ . '/public/') // Run the directory conversion process ->run(MarkdownEnum::TO_HTML_DIRECTORY); if ($markdown) { echo "Directory conversion successful!"; } // If '/docs/guide/*.md' exists, it creates '/public/guide/*.html'.
Single Point Execution
This is the universal executor that can operate in three different modes using the MarkdownEnum enum and run method.
Interface
run( MarkdownEnum $as, ?string $fileName ): mixed;
MarkdownEnum Interface
enum MarkdownEnum { // convert markdown source to raw html (raw/file => raw html) case TO_HTML; // convert markdown source to an html file (markdown raw/file => html file) case TO_HTML_FILE; // convert markdown source directory to html directory (markdown directory => html directory) case TO_HTML_DIRECTORY; }
Usage Examples
Using The MarkdownEnum::TO_HTML Enum
This is an alternative way to call
getHtml().
Markdown::new() ->setContent('# Heading 1') ->run(MarkdownEnum::TO_HTML);
Using The MarkdownEnum::TO_HTML_FILE Enum
This is an alternative way to call
saveToHtmlFile().
Markdown::new() ->addOutputDirectory(__DIR__ . '/build') ->run(MarkdownEnum::TO_HTML_FILE, 'index.html');
Using The MarkdownEnum::TO_HTML_DIRECTORY Enum
This is the only method that uses
setSourceDirectory(). It crawls the source directory, converts all .md files, and saves them (preserving the folder structure) to the output directory.
Markdown::new() ->setSourceDirectory(__DIR__ . '/src/my-docs') ->addOutputDirectory(__DIR__ . '/public/docs') ->run(MarkdownEnum::TO_HTML_DIRECTORY);
🔒 Sanitizing HTML Output (XSS Protection)
You can sanitize input HTML and prevent cross-site scripting (XSS) attack using the sanitize flag.
$sanitize: Set totrue(default) to escape HTML tags in the Markdown. Set tofalseonly if you completely trust the source of your Markdown and need raw HTML to be rendered.
$markdown = Markdown::new( sanitize: true ); $markdown_unsafe = Markdown::new( sanitize: false ); $content = '<h1>Hello World</h1>'; echo $markdown ->setContent($content) ->getHtml(); echo $markdown_unsafe ->setContent($content) ->getHtml();
Output:
Sanitize Enabled: <p><h1>Hello World</h1></p> Sanitize Disabled: <h1>Hello World</h1>
⚙️ Advanced Use Case
Inline Markdown
$markdown = Markdown::new(); $markdown->setInlineContent('_My name is **vincent**, the co-author of this blog_'); echo $markdown->getHtml();
Output:
<i>My name is <strong>vincent</strong>, the co-author of this blog</i>
NOTE: Some markdown symbols are not supported with this method
Example #1
Combine multiple markdown files, contents and compile them in multiple directories:
Header.md
# Blog Title ### Here is the Blog Sub-title
Footer.md
### Thanks for Visiting My BlogPage
index.php
$markdown = Markdown::new(sanitize: true) // include header file's markdown contents ->addFile('./Header.md') // body contents ->setInlineContent('_My name is **vincent**, the co-author of this blog_') ->setContent('Kindly follow me on my GitHub page via: [@vincent](https://github.com/oladoyinbov).') ->setContent('Here are the lists of my projects:') ->setContent(' - Dragon CMS - Fastvolt Framework. + Fastvolt Router + Markdown Parser. ') // include footer file's markdown contents ->addFile(__DIR__ . '/Footer.md') // add the main compilation directory ->addOutputDirectory(__DIR__ . '/pages/') // add another compilation directory to backup the result ->addOutputDirectory(__DIR__ . '/backup/pages/') // compile and store as 'index.html' ->saveToHtmlFile(file_name: 'index.html'); if ($markdown) { echo "Compile Successful. Files created in /pages/ and /backup/pages/"; }
Output:
pages/index.html,backup/pages/index.html
<h1>Blog Title</h1> <h3>Here is the Blog Sub-title</h3> <i>My name is <strong>vincent</strong>, the co-author of this blog</i> <p>Kindly follow me on my github page via: <a href="https://github.com/oladoyinbov">@vincent</a>.</p> <p>Here are the lists of my projects:</p> <ul> <li>Dragon CMS</li> <li>Fastvolt Framework. <ul> <li>Fastvolt Router</li> <li>Markdown Parser.</li> </ul> </li> </ul> <h3>Thanks for Visiting My BlogPage</h3>
Error Handling
The parser uses custom exceptions for clarity:
MarkdownFileNotFound: Thrown when a file specified inaddFile()or a directory insetSourceDirectory()does not exist.LogicException: Thrown if you try to execute a conversion (getHtml()orsaveToHtmlFile()) before any content (setContent, addFile, etc.) has been added to the queue.RuntimeException: Thrown if the system fails to create an output directory (mkdir fails) or if a required directory is missing during run() execution.
🧠 Interface Method Reference
The parser uses a fluent (chainable) API. This is your command cheatsheet for configuration and execution:
| Method Name | Return Type | Description |
|---|---|---|
::new(bool $sanitize = true) |
self |
Initialize the parser instance. The preferred static factory method. |
->setSourceDirectory(string $name) |
static |
Sets the input root directory for whole-directory compilation. |
->setContent(string $content) |
static |
Adds multi-line Markdown content (supports lists, headings, etc.) to the queue. |
->setInlineContent(string $content) |
static |
Adds single-line Markdown content (bold, italic) to the queue. |
->addFile(string $fileName) |
static |
Adds a single Markdown file path to the compilation queue. (Alias: ->setFile()) |
->addMultipleFiles(array $names) |
static |
Adds an array of Markdown file paths to the compilation queue. |
->addOutputDirectory(string $dir) |
static |
Adds a directory where the compiled HTML will be saved. Allows multiple targets. (Alias: ->setCompileDir()) |
->addMultipleOutputDirectories(array $dirs) |
static |
Adds an array of directories where the compiled HTML will be saved. |
->getHtml() |
string|null |
Execute compilation and return the raw HTML string. (Alias: ->toHtml()) |
->saveToHtmlFile(string $name) |
bool |
Execute compilation and write the output to the specified HTML file(s). (Alias: ->toHtmlFile()) |
->run(MarkdownEnum $as, ?string $file) |
mixed |
Universal command to execute conversion based on the specified MarkdownEnum target. |
Supported Formatting Symbols
| Markdown Syntax | Description | Example Syntax | Rendered Output |
|---|---|---|---|
# to ###### |
Headings (H1–H6) | ## Heading 2 |
Heading 2 |
**text** or __text__ |
Bold | **bold** |
bold |
*text* or _text_ |
Italic | *italic* |
italic |
~~text~~ |
Strikethrough | ~~strike~~ |
|
`code` |
Inline code | `echo` |
echo |
|
Code block | ```php\n echo "Hi"; \n``` |
<pre><code>...</code></pre> |
-, +, or * |
Unordered list | - Item 1* Item 2 |
<ul><li>Item</li></ul> |
1. 2. |
Ordered list | 1. Item2. Item |
<ol><li>Item</li></ol> |
[text](url) |
Hyperlink | [GitHub](https://github.com) |
GitHub |
> blockquote |
Blockquote | > This is a quote |
This is a quote |
---, ***, ___ |
Horizontal Rule | --- |
<hr> |
 |
Image |  |
<img src="logo.png" alt="Logo"> |
\ |
Escape special character | \*not italic\* |
not italic (as text) |
✅ Requirements
PHP 8.1 or newer.
ℹ️ Notes
This library is an extended and simplified version of the excellent Parsedown by Erusev.
📄 License
This project is open-source and licensed under the MIT License by @fastvolt.
fastvolt/markdown 适用场景与选型建议
fastvolt/markdown 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 99.31k 次下载、GitHub Stars 达 61, 最近一次更新时间为 2023 年 11 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「markdown」 「markdown-to-html」 「markdown-parser」 「markdown-library」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 fastvolt/markdown 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 fastvolt/markdown 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 fastvolt/markdown 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Texy converts plain text in easy to read Texy syntax into structurally valid (X)HTML. It supports adding of images, links, nested lists, tables and has full support for CSS. Texy supports hyphenation of long words (which reflects language rules), clickable emails and URL (emails are obfuscated again
Pico is a flat file CMS, this means there is no administration backend and database to deal with. You simply create .md files in the "content" folder and that becomes a page.
Pico is a flat file CMS, this means there is no administration backend and database to deal with. You simply create .md files in the "content" folder and that becomes a page.
Adds more BBCode
Markdown to HTML and HTML to Markdown Conversion package
Creates a markdown changelog for your GitHub repository.
统计信息
- 总下载量: 99.31k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 61
- 点击次数: 24
- 依赖项目数: 4
- 推荐数: 1
其他信息
- 授权协议: MIT
- 更新时间: 2023-11-09