PHP fragments in Markdown

Ever wanted to use PHP variables and functions in a markdown file and use that file to generate HTML code from the Markdown syntax? Well, it isn’t too hard…

Assume you want to parse the following file as Markdown, after executing the PHP fragment:

<?php echo $var; ?> 

Some text...

> Maecenas sed diam eget risus varius blandit sit amet non magna.

If you simply use file_get_contents($file);, it will just show the PHP string, in stead of replacing it with the value of the variable. So we want to grab the executed code in a variable and use that variable to generate HTML.

This is done using Output Buffering Control in PHP. We start an output buffer, include the file, and close the output buffer. Everything that would normally be outputted, is now stored in the output buffer.

// start output buffer

// include the markdown file
// working with the output buffer allows us to use php code in the md file.
include $file;

// get the generated content from the output buffer
$md = ob_get_clean();

// parse markdown
$html = md_to_html($md);

Note: If you need newlines in Markdown, you must add a space after the PHP closing tag. I have e.g. added a space after the ?> on the first line to make the markdown parser work.