PHPackages                             sinnbeck/html-ast - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. sinnbeck/html-ast

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

sinnbeck/html-ast
=================

Create an AST from a html string

v1.0.0(1y ago)28MITPHPPHP ^8.2CI passing

Since Apr 14Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/sinnbeck/html-ast)[ Packagist](https://packagist.org/packages/sinnbeck/html-ast)[ RSS](/packages/sinnbeck-html-ast/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

html-ast
========

[](#html-ast)

An HTML AST (Abstract Syntax Tree) parser written in PHP.
Inspired by the AST parser in TempestPHP (by Brett Roose), this library provides a built-in lexer to tokenize HTML strings, an AST parser to convert tokens into a tree structure, and a printer to output well-formatted (indented) HTML.

> **Note:** This package requires PHP 8.2 or higher.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
    - [Lexing](#lexing)
    - [Parsing](#parsing)
    - [Printing](#printing)
- [Testing](#testing)
- [Todo](#todo)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

- **Built-in Lexer:** Tokenizes raw HTML input.
- **AST Parser:** Converts tokenized HTML into an Abstract Syntax Tree for easier analysis and manipulation.
- **HTML Printer:** Renders the AST back into properly indented HTML code.

Requirements
------------

[](#requirements)

- PHP version **8.2** or later.
- Composer (for installation via [Packagist](https://packagist.org/)).

Installation
------------

[](#installation)

You can install **html-ast** via Composer. From your project root, run:

```
composer require sinnbeck/html-ast
```

Alternatively, if you prefer to clone the repository directly:

```
git clone https://github.com/sinnbeck/html-ast.git
cd html-ast
composer install
```

Usage
-----

[](#usage)

The package is organized into three main components: the Lexer, the AST Parser, and the Printer. Below are basic examples of how to use each.

### Lexing

[](#lexing)

The lexer tokenizes an HTML string. Tokens represent the smallest meaningful elements of the HTML (such as tags, attributes, and text).

```
use Sinnbeck\HtmlAst\Lexer\Lexer;

// Provide your HTML string
$html = 'Hello, world!';

// Create a Lexer instance from the string
$lexer = Lexer::fromString($html);

// Lex the HTML string into tokens
$tokens = $lexer->lex();

// Optionally, inspect the tokens:
print_r($tokens);
```

### Parsing

[](#parsing)

The AST parser converts the token list into a tree structure, where each node represents an HTML element, text node, or comment.

```
use Sinnbeck\HtmlAst\Ast\Parser;

// Create an AST parser instance with the tokens from the lexer
$ast = Parser::make($tokens);

// Parse tokens into an AST (node tree)
$nodes = $ast->parse();

// Optionally, inspect the node tree:
print_r($nodes);
```

### Printing

[](#printing)

The printer takes an HTML input or the resulting AST and renders it as neatly formatted HTML. This is useful for ensuring consistent formatting after transformations.

```
use Sinnbeck\HtmlAst\Printer;

// Create a Printer instance and render the HTML string
echo Printer::make($nodes)->render();
```

If you need to indent all lines by a certain level, you can easily do so.

```
use Sinnbeck\HtmlAst\Printer;

// Indents everything by 1 extra indentation level
echo Printer::make($nodes)->render(1);
```

By default, the output is indented with 4 spaces. This can be easily changed by calling `->withIndent()`

```
use Sinnbeck\HtmlAst\Printer;

// Indents with tab instead of 4 spaces
echo Printer::make($nodes)->indentWith("\t")->render();
```

Testing
-------

[](#testing)

The repository includes tests under the `tests` directory, using [Pest PHP](https://pestphp.com/) as the testing framework and Symfony's VarDumper for debugging. To run tests, execute:

```
composer test
```

This command runs all tests to ensure the lexing, parsing, and printing functionalities work as expected.

Todo
----

[](#todo)

- Add line numbers to tokens (Lexer)
- Introduce an HTML validator to ensure that the HTML structure conforms to expected standards
- Implement a node visitor pattern to allow modification or transformation of the AST

Contributing
------------

[](#contributing)

Contributions to **html-ast** are welcome. If you would like to contribute, please follow these steps:

1. Fork the repository.
2. Create a feature branch: ```
    git checkout -b feature/your-feature-name
    ```
3. Make your changes and add tests.
4. Format all files: ```
    ./vendor/bin/pint`
    ```
5. Commit your changes: ```
    git commit -am 'Add new feature'
    ```
6. Push the branch: ```
    git push origin feature/your-feature-name
    ```
7. Open a pull request explaining your changes.

Please adhere to the coding standards and test all changes before submitting a pull request.

License
-------

[](#license)

This project is licensed under the [MIT License](https://opensource.org/license/MIT)

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance54

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

400d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ac448dc0df3a332cc0f75645f718a27abb7cf8c69b554bde7b643badd1cf99d6?d=identicon)[Sinnbeck](/maintainers/Sinnbeck)

---

Top Contributors

[![sinnbeck](https://avatars.githubusercontent.com/u/13980140?v=4)](https://github.com/sinnbeck "sinnbeck (26 commits)")

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/sinnbeck-html-ast/health.svg)

```
[![Health](https://phpackages.com/badges/sinnbeck-html-ast/health.svg)](https://phpackages.com/packages/sinnbeck-html-ast)
```

###  Alternatives

[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M65](/packages/sabberworm-php-css-parser)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)[jms/serializer-bundle

Allows you to easily serialize, and deserialize data of any complexity

1.8k89.3M627](/packages/jms-serializer-bundle)[hassankhan/config

Lightweight configuration file loader that supports PHP, INI, XML, JSON, and YAML files

97513.5M170](/packages/hassankhan-config)[meyfa/php-svg

Read, edit, write, and render SVG files with PHP

54613.9M42](/packages/meyfa-php-svg)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
