Markdown is a text-to-HTML conversion tool for web writers. It has gained its deserved popularity after its introduction on 2004. Markdown allows you to write text while providing a format in an easy and clean way.

Though it is developed by Perl, it has been ported to different languages such as PHP. In this tutorial, we will show you how to parse markdown in PHP. There is already a library league/commonmark developed by PHP League and it supports full CommonMark spec. We will be using this package across the tutorial.

Table Of Content

  1. Processing headers
  2. Processing lists
  3. Processing image
  4. Processing table
  5. The end
1. Processing headers

First thing first, let's install league/commonmark using Composer as usual.

In the first example, we need to parse file headers.md which contains content as shown below:

# This is an H1

## This is an H2

###### This is an H6

We will first include the autoloader from Composer vendor folder. Then we will import CommonMarkConverter class and instantiate an instance of it. At last, we use the method convertToHtml to parse the content of headers.md.

The outcome of running the script above is as shown below:

2. Processing lists

In this example, we need to parse file lists.md which contains content as shown below:

* This is a
* This is b
* This is c

+ This is A
+ This is B
+ This is C

Similar to the previous example, we use the same method convertToHtml to do the job for us.

The outcome of running the script above is as shown below:

3. Processing link

In this example, we need to parse file link.md which contains content as shown below:

[this is a link](www.google.com)

Similar to previous example, we use the same method convertToHtml to do the job for us.

We will again use the same method:

The outcome of running the script above is as shown below:

4. Processing table

In this example, we need to parse file table.md which contains content as shown below:

th | th(center) | th(right)
---|:----------:|----------:
td | td         | td

CommonMark is not able to parse table out of box, we need to install an extension to make that possible.

We will create an environment, then add the table extension to the environment. Then create a converter using the environment. At last, we parse the markdown file as normal.

The outcome of running the script above is as shown below:

5. The end

Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.