For a few years, I have been using PHP Parsedown in SqlSiteServer. (That's the CMS of my website.) PHP Parsedown is an easy-to-use one-include-file PHP implementation of the canonical MarkDown. I have been using the more standardized CommonMark dialect for my books. I have been wanting to use the same dialect for my CMS as well. Most searches lead to something called PHPLeague CommonMark. Using it is not so straightforward as PHP Parsedown. I just need one method to parse a string containing CommonMark text and have it converted to HTML. The PHPLeague seemed to give the proverbial banana and also the monkey and the forest attached to it.
Browsing through PHP documentation, I found that there exists native PHP support in the form of an extension. It did not come as part of the default install. It had to downloaded from a PHP extensions marketplace using a software called PEAR.
Installing the cmark extension
PEAR also requires the development library of PHP and cmark.
sudo apt install php-pear php7.4-dev libcmark-dev
PEAR may not know where your PHP installation is so let it know about the location of the PHP.ini file.
pear config-set php_ini /etc/php/7.4/apache2/php.ini
Then, download the latest cmark PHP extension tarball from the site:
Next, install the tarball using PEAR.
sudo pear install cmark-1.2.0.tgz
After the installation, restart the Apache server dæmon.
sudo service apache2 restart
You can now check if the extension has been installed using:
<?php
echo phpinfo();
?>
Using the cmark extension
Finally, use the extension to convert some makdown to HTML.
<?php
$sMarkDown="**Hello, World!**";
$oNode = CommonMark\Parse($sMarkDown);
echo CommonMark\Render\HTML($oNode);
?>
If you are using the methods in your own namespaces or class, do remember to rewrite the code as:
$sMarkDown="**Hello, World!**";
$oNode = \CommonMark\Parse($sMarkDown);
echo \CommonMark\Render\HTML($oNode);
The extension is very fast, as it is written in C. There are no use directives or include files to mess with.
‘CommonMark Ready Reference’ updated
The above information was added to my book on CommonMark. I had also updated the cover.
Future tasks
The pear list-all command and PECL site listed a lot of PHP extensions with which a PHP site can be greatly enhanced. I need to browse them later.
UPDATE (30-December-2022)
By default, the extension omits raw HTML. There is another option.
define("CMARK_OPT_UNSAFE", (1 << 17));
…
$oCmDoc = \CommonMark\Parse($asMarkdown);
$sHtml = \CommonMark\Render\HTML($oCmDoc, CMARK_OPT_UNSAFE);
