EDDYMENS

Get The Metadata Header From A Markdown File Using PHP

In this short write-up I have put together PHP code that reads a markdown file, extracts its YAML-based meta header, allows you to modify it then updates the original markdown file with the changes.

content/sample.md


01: ---
02: title: 'Original title'
03: description: 'Some description'
04: ---
05: 
06: # heading
07: 
08: content goes here

headerParser.php


01: <?php
02: 
03: use Symfony\Component\Yaml;
04: 
05: $markdownFilePath = 'content/sample.md';
06: $markdownContent = file_get_contents($markdownFilePath);
07: 
08: $headerRegex = '/^---([\s\S]*?)---/';
09: preg_match($headerRegex, $markdownContent, $matches);
10: $content = str_replace($matches[0], '', $markdownContent);
11: 
12: try {
13:     $header = Yaml::parse($matches[1]);
14:     $header['title'] = 'Changed title';
15:     $updatedHeader = Yaml::dump($header);
16:     $updatedMarkdownContent = "---\n".$updatedHeader."---".$content;
17:     $markdownContent = file_put_contents($markdownFilePath, $updatedMarkdownContent);
18: } catch (Exception $e) {
19:     var_dump($e);
20:     die;
21: }
22: 

Explanation

  • Line 03: The Symfony Yaml Component [↗] is used to convert the header to an array, so you can access the header attributes. You will need to autoload [↗] the package or use the include statement to pull it in.
  • Line 05 - 06: The markdown file content is fetched so we can process it.
  • Line 08 - 10: The regex statement is used to extract the header from the content section. The content is then saved to the $content variable.
  • Line 13 - 16: In this code sample we replaced the existing tile with 'Changed title', then wrote the changes back to the markdown file.

Here is another article you might like 😊 "A Way To Avoid Filling In Required Fields"