BEST-WEB-TOOLS Blog

My own blog posts about development, tech, finance and other (interesting) stuff.

❮❮ back

2021-06-18, Dev, PHP, Markdown, Frontmatter

PHP Markdown Library with Front Matter

For this blog I was looking for a PHP Markdown library that is easy to use and also clean and extensible. The idea was, that I just write the blog posts in Markdown and don't have any sort of index-file or any other meta-data except things that could be included into the blog post itself.

For such a requirement there is an extension to Markdown called "Front Matter". It is comming from YAML and is basically a block of meta data seperated by dashes at the beginning of a file. Front Matter supports key-value pairs and lists. Here is the Front Matter of this blog post ...


layout: post
slug: php-markdown-library-frontmatter
title: PHP Markdown Library with Front Matter
category: dev
date: 2021-06-18
tags:
    - PHP
    - Markdown
    - Front Matter

CommonMark for PHP from The League of Extraordinary Packages is the best markdown library i found so far. It is hosted on GitHub, has 1.9k stars and the current stable version 1.6.2 is from May 2021. There is already a 2.0 upcomming that i used here. It supports some markdown dialects like the GitHub-Flavored Markdown and it has a nice list of extensions. Besides Front Matter you could find extensions for task lists, auto linking and tables.

The Front Matter extension in CommonMark 2.0 gives you access to the meta data as an associative array. Look at the example and find more in the CommonMark docs


$environment = new Environment([]);

$environment->addExtension(new CommonMarkCoreExtension());
$environment->addExtension(new FrontMatterExtension());

$converter = new MarkdownConverter($environment);
$result = $converter->convertToHtml($markdown);

if ($result instanceof RenderedContentWithFrontMatter) {
    $frontMatter = $result->getFrontMatter();
}

var_dump($frontMatter);



❮❮ back