Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
YAML Front Matter
https://github.com/spatie/yaml-front-matter
Admin
A YAML front matter parser for PHP that extracts metadata from files with YAML content wrapped in
...
Tokens:
6,062
Snippets:
42
Trust Score:
8.5
Update:
3 days ago
Context
Skills
Chat
Benchmark
89.3
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# YAML Front Matter YAML Front Matter is a PHP library for parsing YAML front matter from text content and files. Front matter is metadata written in YAML format, typically located at the top of a file wrapped between triple-dash delimiters (`---`). This pattern is commonly used in static site generators like Jekyll, Hugo, and other content management systems to embed structured metadata alongside document content. The library provides a clean, intuitive API for extracting both the YAML metadata and the body content separately. It supports dot notation for accessing nested properties, magic property access for convenient retrieval, and includes a specialized parser for handling complex Markdown files that may contain front matter examples within code blocks. Built on top of Symfony's YAML component, it handles edge cases like empty front matter, missing newlines, and Windows-style line endings gracefully. ## Installation ```bash composer require spatie/yaml-front-matter ``` ## YamlFrontMatter::parse() Parses a string containing YAML front matter and returns a Document object with the extracted matter and body content. The front matter must be enclosed between two `---` delimiters at the beginning of the content. If no valid front matter is found, returns an empty matter array with the full content as the body. ```php <?php use Spatie\YamlFrontMatter\YamlFrontMatter; $content = <<<MD --- title: My Blog Post author: John Doe tags: - php - tutorial published: true --- # Welcome to My Blog This is the main content of the post. MD; $document = YamlFrontMatter::parse($content); // Get all front matter as an array $matter = $document->matter(); // Returns: ['title' => 'My Blog Post', 'author' => 'John Doe', 'tags' => ['php', 'tutorial'], 'published' => true] // Get a specific front matter value $title = $document->matter('title'); // Returns: 'My Blog Post' // Get the body content (everything after the closing ---) $body = $document->body(); // Returns: "# Welcome to My Blog\n\nThis is the main content of the post." ``` ## YamlFrontMatter::parseFile() Reads and parses a file directly from the filesystem without needing to manually read its contents. This is a convenience method that wraps file_get_contents() and parse() into a single call. ```php <?php use Spatie\YamlFrontMatter\YamlFrontMatter; // Parse a markdown file directly $document = YamlFrontMatter::parseFile('/path/to/blog-post.md'); // Access front matter $title = $document->matter('title'); $author = $document->matter('author'); // Get the body content $content = $document->body(); // Example: Processing multiple markdown files $files = glob('/path/to/posts/*.md'); foreach ($files as $file) { $document = YamlFrontMatter::parseFile($file); echo "Title: " . $document->matter('title') . "\n"; echo "Body length: " . strlen($document->body()) . " characters\n"; } ``` ## YamlFrontMatter::markdownCompatibleParse() A specialized parser for handling Markdown files that contain front matter examples within code blocks. The standard parser may incorrectly interpret `---` delimiters inside code blocks as front matter boundaries. This method uses line-by-line analysis to correctly identify only the actual front matter at the document's beginning. ```php <?php use Spatie\YamlFrontMatter\YamlFrontMatter; // Content with front matter AND code blocks containing front matter examples $content = <<<MD --- title: Front Matter Tutorial category: documentation --- # How to Use Front Matter Here's an example of front matter syntax: ```yaml --- title: Example Post author: Jane Doe --- Content goes here... ``` The code block above won't be parsed as actual front matter. MD; // Use markdownCompatibleParse for complex markdown with embedded examples $document = YamlFrontMatter::markdownCompatibleParse($content); // Only the actual front matter is extracted $matter = $document->matter(); // Returns: ['title' => 'Front Matter Tutorial', 'category' => 'documentation'] // The body includes the code block intact $body = $document->body(); // Contains the full markdown including the code block with front matter example ``` ## Document::matter() Retrieves front matter values from the parsed document. When called without arguments, returns all front matter as an associative array. When called with a key, returns that specific value. Supports dot notation for accessing nested properties and accepts a default value for missing keys. ```php <?php use Spatie\YamlFrontMatter\YamlFrontMatter; $content = <<<MD --- title: Advanced Configuration version: 2.0 meta: keywords: - php - yaml - parser author: name: Sebastian De Deyne email: sebastian@spatie.be settings: debug: false cache_ttl: 3600 --- Document content here. MD; $document = YamlFrontMatter::parse($content); // Get all front matter $allMatter = $document->matter(); // Returns full nested array structure // Get top-level value $title = $document->matter('title'); // Returns: 'Advanced Configuration' // Get nested value using dot notation $authorName = $document->matter('meta.author.name'); // Returns: 'Sebastian De Deyne' $keywords = $document->matter('meta.keywords'); // Returns: ['php', 'yaml', 'parser'] // Get deeply nested value $cacheTtl = $document->matter('settings.cache_ttl'); // Returns: 3600 // Use default value for missing keys $description = $document->matter('description', 'No description available'); // Returns: 'No description available' $missingNested = $document->matter('meta.social.twitter', '@default'); // Returns: '@default' ``` ## Document::body() Returns the body content of the document as a string. The body is everything that appears after the closing `---` delimiter, with leading whitespace trimmed appropriately. ```php <?php use Spatie\YamlFrontMatter\YamlFrontMatter; $content = <<<MD --- title: Getting Started --- ## Introduction Welcome to the documentation. This guide will help you get started. ### Prerequisites - PHP 8.0 or higher - Composer installed ### Installation Steps 1. Run composer require 2. Configure your settings 3. Start using the library MD; $document = YamlFrontMatter::parse($content); // Get the full body content $body = $document->body(); // The body contains all content after the front matter echo $body; // Output: // ## Introduction // // Welcome to the documentation. This guide will help you get started. // // ### Prerequisites // ... // Common use case: Render markdown body with a markdown parser // $html = (new Parsedown())->text($document->body()); ``` ## Magic Property Access The Document class implements `__get()` magic method, allowing front matter values to be accessed as object properties. This provides a more convenient syntax for accessing top-level front matter keys. ```php <?php use Spatie\YamlFrontMatter\YamlFrontMatter; $content = <<<MD --- title: My Article author: John Smith date: 2024-01-15 published: true tags: - news - featured --- Article content goes here. MD; $document = YamlFrontMatter::parse($content); // Access front matter as properties $title = $document->title; // Returns: 'My Article' $author = $document->author; // Returns: 'John Smith' $date = $document->date; // Returns: '2024-01-15' $published = $document->published; // Returns: true $tags = $document->tags; // Returns: ['news', 'featured'] // Undefined properties return null $category = $document->category; // Returns: null // Example: Building a blog post object $post = (object) [ 'title' => $document->title, 'author' => $document->author, 'date' => new DateTime($document->date), 'content' => $document->body(), 'isPublished' => $document->published ?? false, ]; ``` ## Handling Edge Cases The parser handles various edge cases gracefully including empty front matter, missing content, invalid delimiters, and content without front matter. ```php <?php use Spatie\YamlFrontMatter\YamlFrontMatter; // Content with no front matter - returns empty matter, full content as body $noFrontMatter = "Just regular content without any front matter."; $doc1 = YamlFrontMatter::parse($noFrontMatter); $doc1->matter(); // Returns: [] $doc1->body(); // Returns: "Just regular content without any front matter." // Front matter with no body $noBody = "---\ntitle: Metadata Only\n---"; $doc2 = YamlFrontMatter::parse($noBody); $doc2->matter(); // Returns: ['title' => 'Metadata Only'] $doc2->body(); // Returns: "" // Front matter with no newline after closing delimiter $noNewline = "---\ntitle: Compact\n---"; $doc3 = YamlFrontMatter::parse($noNewline); $doc3->matter('title'); // Returns: 'Compact' // Invalid/incomplete front matter (only one delimiter) $invalid = "---\nfoo: bar\n\nThis is not valid front matter."; $doc4 = YamlFrontMatter::parse($invalid); $doc4->matter(); // Returns: [] $doc4->body(); // Returns the original content // Front matter value containing delimiter characters $withDelimiter = "---\ntitle: Section---Subsection\n---\nContent"; $doc5 = YamlFrontMatter::parse($withDelimiter); $doc5->matter('title'); // Returns: 'Section---Subsection' ``` ## Summary YAML Front Matter is ideally suited for static site generators, content management systems, documentation tools, and any application that needs to associate structured metadata with text content. Common use cases include blog post metadata (title, author, date, tags), page configuration (layout, template, navigation settings), documentation properties (version, API reference links), and content organization (categories, weights, draft status). The library integrates seamlessly with PHP applications through Composer and pairs well with Markdown parsers like Parsedown or CommonMark for building complete content pipelines. The combination of static parsing methods, dot notation for nested properties, and magic property access makes it simple to incorporate into existing workflows while handling the full range of edge cases that arise when processing user-generated content files.