League/commonmark is a highly extensible PHP Markdown parser. It fully supports the CommonMark specification and GitHub-Flavored Markdown. This makes it an ideal choice when you need to convert CommonMark or GitHub-Flavored Markdown into HTML. The package was created by Colin O'Dell and based on the CommonMark JS reference implementation by John MacFarlane.
To use league/commonmark in your PHP project, you first need to install it via Composer. Run the following command in your terminal:
$ composer require league/commonmark
After that, you can utilize the CommonMarkConverter
or GithubFlavoredMarkdownConverter
classes to convert your markdown text into HTML. Below is sample usage of the CommonMarkConverter
:
use League\CommonMark\CommonMarkConverter;
$converter = new CommonMarkConverter([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
echo $converter->convert('# Hello World!');
// <h1>Hello World!</h1>
If instead you want GitHub-Flavored Markdown, you can use the GithubFlavoredMarkdownConverter
class:
use League\CommonMark\GithubFlavoredMarkdownConverter;
$converter = new GithubFlavoredMarkdownConverter([
'html_input' => 'strip',
'allow_unsafe_links' => false,
]);
echo $converter->convert('# Hello World!');
// <h1>Hello World!</h1>
Make sure to only use UTF-8 and ASCII encodings with these converters. If you're parsing untrusted input, consider setting the html_input
and allow_unsafe_links
options for additional security.
Full documentation for league/commonmark, including advanced usage, configuration, and customization information, can be found at https://commonmark.thephpleague.com. This comprehensive resource provides everything you need to unlock the full potential of the league/commonmark package.