MarkDownify
MarkDownify is a PHP library that simplifies the process of parsing Markdown into HTML code. It provides compatibility with the specifications of GitHub Flavored Markdown, making it a versatile tool for working with Markdown content.
Features
-
Conversion of headings, emphasis, strong emphasis, and strikethrough.
-
Support for fenced code blocks with syntax highlighting.
-
Task lists, tables, footnotes, and definition lists.
-
Inline code, links, and images.
-
Support for horizontal rules, blockquotes, and ordered/unordered lists.
-
Highlighting, subscript, and superscript.
-
Emojis.
Requirements
Installation
You can install MarkDownify via Composer. Run the following command:
composer require kuasarx/markdownify
Usage
To use MarkDownify in your PHP project, follow these steps:
-
Require the autoloader generated by Composer:
require 'vendor/autoload.php';
-
Create a new instance of the `MarkDownify` class:
use MarkDownify\MarkDownify;
$text = "Your Markdown content";
$parser = new MarkDownify($text);
-
Parse the Markdown content into HTML:
$html = $parser->parse();
-
Use the parsed HTML in your application as needed.
CSS Styling
Here's how you can add CSS to the page to achieve a GitHub-like look:
- Include GitHub Markdown CSS
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css">
-
Style Your Container:
Wrap the generated HTML output from MarkDownify in a `<div>` element with the class `markdown-body`. This class is defined in the GitHub Markdown CSS and applies the styling consistent with GitHub's Markdown rendering.
echo '<div class="markdown-body">' . $html . '</div>';
Examples
Example 1: Basic Usage
use MarkDownify\MarkDownify;
// Markdown content
$text = "# Hello, MarkDownify!\n\nThis is bold and italic text.";
// Create a new instance of MarkDownify
$parser = new MarkDownify($text);
// Parse Markdown into HTML
$html = $parser->parse();
echo $html;
Example 2: Convert Task List
use MarkDownify\MarkDownify;
// Markdown content with a task list
$text = "- [x] Task 1\n- [ ] Task 2\n- [x] Task 3";
// Create a new instance of MarkDownify
$parser = new MarkDownify($text);
// Parse Markdown into HTML
$html = $parser->parse();
echo $html;
Example 3: Convert Table
use MarkDownify\MarkDownify;
// Markdown content with a table
$text = "| Name | Age | Gender |\n|-------|-----|--------|\n| John | 30 | Male |\n| Alice | 25 | Female |";
// Create a new instance of MarkDownify
$parser = new MarkDownify($text);
// Parse Markdown into HTML
$html = $parser->parse();
echo $html;
MarkDownify is released under the MIT License. See LICENSE for more information.