Render Markdown/GFM Documents online using the GitHub v3 API
simple code snipped to convert markdown to html, public github api
Sometimes, you need to render parts of your Markdown documents – e.g. README.md or CHANGES.md – as html to embed it into your application, documentation or project website. There are a several markdown or especially GFM (GitHub Flavored Markdown) libraries are out there, but they require an additional setup and have to be maintained.
The simple Way#
Thanks to GitHub, there is a public API available which allows you to render your documents by the GitHub webservices.
PHP Client#
/** * Render Markdown content using the GitHub v3 Markdown API * @see https://developer.github.com/v3/markdown/ * @source https://andidittrich.com/2016/05/render-markdown-gfm-documents-online-using-the-github-v3-api * @license: MIT * @return string(html) */ function renderGFM($text, $repositoryContext = null){ // create the payload // @see https://developer.github.com/v3/markdown/ $postdata = json_encode( array( 'text' => $text, 'mode' => ($repositoryContext != null ? 'gfm' : 'markdown'), 'context' => $repositoryContext ) ); // prepare the HTTP 1.1 POST Request $opts = array('http' => array( 'method' => 'POST', 'protocol_version' => '1.1', 'user_agent' => $repositoryContext, 'header' => array( 'Content-type: application/x-www-form-urlencoded;charset=UTF-8', 'Connection: close', 'Accept: application/vnd.github.v3+json' ), 'content' => $postdata ) ); // send request return file_get_contents('https://api.github.com/markdown', false, stream_context_create($opts)); }
Usage#
The optional $repositoryContext
argument allows your to define the context which should be used for rendering to e.g. enable issue linking
// fetch the document (example) $document = file_get_contents('https://raw.githubusercontent.com/AndiDittrich/WordPress.Enlighter/master/CHANGES.md'); // render html using the GitHub GFM API $html = renderGFM($document, 'AndiDittrich/WordPress.Enlighter'); // show it! echo $html;