# 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 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 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 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 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 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 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 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.