Working with Markdown in PHP: Overview of Libraries and Tools
Markdown is a lightweight markup language that allows you to create formatted text using simple syntax. In PHP, there are several mature and reliable libraries for processing Markdown. In this article, we will look at three of the most popular tools: Parsedown, PHP-Markdown, and League/CommonMark.
1. Parsedown — Lightweight and Fast Parser
Parsedown is one of the most popular libraries for working with Markdown in PHP. It requires no external dependencies, supports all basic markup elements, and works very quickly.
Installation
composer require erusev/parsedownBasic Usage
<?phprequire 'vendor/autoload.php';
$Parsedown = new Parsedown();
$markdown = <<<MARKDOWN# Heading Level 1
This is **bold text** and *italic*.
- List item 1- List item 2
[Link to PythonLib](https://pythonlib.ru)MARKDOWN;
echo $Parsedown->text($markdown);?>The result of executing this code is valid HTML with headings, lists, and links.
Additional Features
- Safe mode support (escaping HTML tags)
- Working with nested lists and tables
- Configuration via
setBreaksEnabled()andsetMarkupEscaped()methods
2. PHP-Markdown — Classic Solution
PHP-Markdown is the original Markdown parser implementation by Michel Fortin, based on John Gruber's Perl version. This library strictly follows the Markdown specification.
Installation
composer require michelf/php-markdownUsage Example
<?phprequire 'vendor/autoload.php';
use Michelf\\Markdown;
$markdown = <<<MARKDOWN## Heading Level 2
> This is a blockquote.> It can be multi-line.
1. First numbered list item2. Second item
`inline code` and a code block:
<?php echo "Hello, World!"; ?>MARKDOWN;
$html = Markdown::defaultTransform($markdown);echo $html;?>Features
- Support for extended syntax via MarkdownExtra
- Automatic conversion of links and email addresses
- Ability to disable HTML in output
3. League/CommonMark — Standardized Implementation
League/CommonMark is a library implementing the official CommonMark standard. It ensures maximum compatibility with other parsers and supports extensions.
Installation
composer require league/commonmarkExample with Extensions
<?phprequire 'vendor/autoload.php';
use League\\CommonMark\\Environment\\Environment;use League\\CommonMark\\Extension\\CommonMark\\CommonMarkCoreExtension;use League\\CommonMark\\MarkdownConverter;
// Create an environment with base extensions$environment = new Environment();$environment->addExtension(new CommonMarkCoreExtension());
$converter = new MarkdownConverter($environment);
$markdown = <<<MARKDOWN| Table | Column 1 | Column 2 ||-------|----------|----------|| Row 1 | Value | Value || Row 2 | Value | Value |
~~Strikethrough text~~ and ==highlighted text== (GFM).MARKDOWN;
echo $converter->convert($markdown)->getContent();?>Additional Extensions
- Table — table support
- Strikethrough — strikethrough text
- TaskList — checkboxes
- Autolink — automatic links