Thursday, 3 July 2025

Generating llms.txt files with PHP

To make your website or project site provide LLM-friendly content, there's a new standard on the horizon named /llms.txt. It suggests adding a llms.txt containing human and LLM readable content in a fixed Markdown format.

Using llms-txt-php

In the PHP ecosystem, there's a relatively fresh PHP 📦 for writing, reading, and validating llms.txt Markdown files. The following snippet shows how to programmatically model such a file.
use Stolt\LlmsTxt\LlmsTxt;
use Stolt\LlmsTxt\Section;
use Stolt\LlmsTxt\Section\Link;

$section1 = (new Section())->name('Section name')
    ->addLink((new Link())->urlTitle('Link title')
        ->url('https://link_url')->urlDetails('Optional link details')
    );
$section2 = (new Section())->name('Optional')
    ->addLink((new Link())->urlTitle('Link title')
        ->url('https://link_url')
    );

$llmsTxt = (new LlmsTxt())->title('Test title')
  ->description('Test description')
  ->details('Test details')
  ->addSections([$section1, $section2])
  ->addSection($section2)
  ->toString();
Reading a llms.txt file and its parts are done the following way.
use Stolt\LlmsTxt\LlmsTxt;

$llmsText = (new LlmsTxt())->parse('/path/to/llmsTxt.md');

if ($llmsText->validate()) {
    $title = $llmsText->getTitle();
    $description = $llmsText->getDescription();
    $details = $llmsText->getDetails();
    $sections = $llmsText->getSections();
}
The llms-txt-php package also provides a minimalistic CLI to interact with an existing llms.txt file or boostrap it's creation. The following console output lists the currently available commands.
php bin/llms-txt list

llms-txt-php 1.6.1

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display help for the given command. When no command is given display help for the list command
      --silent          Do not output any message
  -q, --quiet           Only errors are displayed. All other output is suppressed
  -V, --version         Display this application version
      --ansi|--no-ansi  Force (or disable --no-ansi) ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  check-links  Check links of a llms txt file
  completion   Dump the shell completion script
  help         Display help for a command
  info         Get metadata info of a llms txt file
  init         Create an initial llms txt file
  list         List commands
  validate     Validate the given llms txt file

No comments: