PHPackages                             artyuum/html-element - 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. [Templating &amp; Views](/categories/templating)
4. /
5. artyuum/html-element

ActiveLibrary[Templating &amp; Views](/categories/templating)

artyuum/html-element
====================

A PHP class giving you the ability to generate HTML elements.

4.0.0(5y ago)7348↓73.3%11MITPHPPHP ^7.4 || ^8.0CI failing

Since May 4Pushed 3y ago2 watchersCompare

[ Source](https://github.com/artyuum/html-element)[ Packagist](https://packagist.org/packages/artyuum/html-element)[ RSS](/packages/artyuum-html-element/feed)WikiDiscussions master Synced 6d ago

READMEChangelog (6)Dependencies (1)Versions (7)Used By (1)

HtmlElement
===========

[](#htmlelement)

A PHP library giving you the ability to generate HTML elements in an object oriented way.

Why did I create this ?
-----------------------

[](#why-did-i-create-this-)

I used to work on a non-MVC PHP project and sometimes I needed to output few lines of HTML directly from the functions. Having to mix HTML code in PHP code was inconsistent to me and it was hard to keep the code easily readable and easy to maintain in the longterm because of the crazy and ugly concatenations. That's why I came up with the idea of generating HTML elements directly in PHP. (of course if you need to create many HTML elements, you should consider using a templating engine instead)
There are few existing libraries on Packagist that have the same purpose but I wasn't really satisfied and I also wanted to create my own library for fun &amp; learning purpose.

Features
--------

[](#features)

- Supports self-closing tags. (e.g input tag)
- Supports boolean attributes. (e.g required attribute)

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

[](#requirements)

- PHP ^7.4 or PHP ^8.0
- Composer

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

[](#installation)

```
composer require artyuum/html-element

```

Examples
--------

[](#examples)

### Simple

[](#simple)

A simple DIV element with some attributes &amp; a content.

```
use Artyum\HtmlElement\Element;
use Artyum\HtmlElement\Attribute;

$divElement = new Element('div');

$divElement
    ->addAttributes(
        new Attribute('title', 'This is an editable DIV with a red background color'),
        new Attribute('style', [
                'width: 100px',
                'height: 100px',
                'background-color: red'
        ]),
        new Attribute('contenteditable', true)
    )
    ->addContent('This is an editable DIV with a red background color.')
;

echo $divElement;
// or
echo $divElement->toHtml();
```

**Output**

```

    This is an editable DIV with a red background color.

```

### Advanced

[](#advanced)

An example of a login form that contains children.

```
use Artyum\HtmlElement\Element;
use Artyum\HtmlElement\Attribute;

$formElement = new Element('form');
$divElement = new Element('div');
$labelElement = new Element('label');
$usernameInputElement = new Element('input');
$passwordInputElement = new Element('input');
$buttonElement = new Element('button');
$spanElement = new Element('span');

$formElement
    ->addAttributes(
        new Attribute('action', '/login'),
        new Attribute('method', 'post')
    )
    ->addContent(
        $divElement
            ->addAttributes(new Attribute('class', 'form-group'))
            ->addContent(
                $labelElement
                    ->addAttributes(new Attribute('for', 'username'))
                    ->addContent('Username'),
                $usernameInputElement
                    ->addAttributes(
                        new Attribute('type', 'text'),
                        new Attribute('class', 'form-control'),
                        new Attribute('id', 'username'),
                        new Attribute('name', 'username'),
                        new Attribute('placeholder', 'Username'),
                        new Attribute('style', [
                            'border: none',
                            'background-color: rgba(100, 100, 255, .1)'
                        ]),
                        new Attribute('required', true)
                    ),
                $passwordInputElement
                    ->addAttributes(
                        new Attribute('type', 'password'),
                        new Attribute('class', 'form-control'),
                        new Attribute('id', 'password'),
                        new Attribute('name', 'password'),
                        new Attribute('placeholder', 'Password'),
                        new Attribute('style', [
                            'border: none',
                            'background-color' => 'rgba(100, 100, 255, .1)'
                        ]),
                        new Attribute('required', true)
                    ),
                $buttonElement
                    ->addAttributes(new Attribute('type', 'submit'))
                    ->addContent(
                        $spanElement
                            ->addAttributes(new Attribute('class', 'fa fa-sign-in-alt'))
                            ->addContent('Login')
                    )
            )
    );

echo $formElement;
// or
echo $formElement->toHtml();
```

**Output**

```

        Username

        Login

```

API
---

[](#api)

### Artyum\\HtmlElement\\Element

[](#artyumhtmlelementelement)

When instantiating the `Element` class, you can optionally provide the name of the element as first argument, and an array of options as second argument.

```
__construct(?string $name = null, ?array $options = null)
```

---

Gets the HTML code of the element.

```
toHtml(): string
```

If you call this method without setting the name property first, a `LogicException` will be thrown.

Note that you can also simply `echo` the instance and it will internally call the `toHtml()` method. This is possible thanks to the `__toString()` magic method.

**Example**

```
// both will return the same result
echo $element->toHtml();
echo $element;
```

---

Gets the name of the element.

```
getName(): ?string
```

---

Sets the name of the element.

```
setName(string $name): self
```

---

Gets the options of the element.

```
getOptions(): ?array
```

---

Sets the options of the element.

```
setOptions(array $options): self
```

**Available options :**

NameTypeDescriptionautoclosebooleanWhether the element should have closing tag or not.---

Gets the attributes assigned to the element.

```
getAttributes(): Attribute[]
```

---

Adds one or multiple attributes to the element.

```
addAttributes(... Attribute $attribute): self
```

Thanks to the splat operator (...), you can pass as much argument as you want. You can also call this method multiple times to add additional attributes.

---

Returns the content of the element.

```
getContent(): ?string
```

---

Adds one or multiple contents to the element. You can pass a string, an integer, a float or an instance of the Element class.

```
addContent(...$content): self
```

### Artyum\\HtmlElement\\Attribute

[](#artyumhtmlelementattribute)

When instantiating the `Attribute` class, you must provide the name of the attribute and its value. You can optinally pass the separator that will be used to separate the values if you pass an array of values.

```
__construct(?string $name = null, mixed $value = null, string $separator = ';')
```

---

Gets the name.

```
getName(): ?string
```

---

Sets the name.

```
setName(string $name): self
```

---

Gets the value.

```
getValue(): mixed
```

---

Sets the value.

```
setValue(mixed $value): self
```

---

Gets the separator.

```
getSeparator(): string
```

---

Sets the attribute values separator.

```
setSeparator(string $separator): self
```

---

Builds &amp; returns the HTML representation of the attribute.

```
build(): string
```

If you call this method without setting the name or the value property first, a `LogicException` will be thrown.

You can also `echo` the instance and it will internally call the `build()` method.

Changelog
---------

[](#changelog)

This library follows [semantic versioning](https://semver.org/).

- **4.0.0** - (2021-05-13)

    - Set Attribute class constructor arguments as optional
    - Added the name and value setter in Attribute
    - Now throwing an exception if the name or the value is not set when calling build() on Attribute
    - Set Element class constructor arguments as optional
    - Added name setter in Element
    - Now throwing an exception if the name is not set when calling toHtml() on Element
    - **Now compatible with PHP 8**
- **3.0.0** - (2020-09-21)

    - Renamed HtmlElement to Element.
    - Added a new Attribute class.
    - Renamed setContent to addContent().
    - Removed setName() and made $name required when instantiating the Element class.
    - Removed native support of style attribute in favor of a new way to handle attributes using the Attribute class.
    - Removed WrongAttributeValueException in favor of InvalidArgumentException.
    - addAttributes() can now accept one or multiple arguments.
    - Updated tests according to the new changes.
- **2.0.1** - (2020-01-22)

    - Simplified buildAttributes() &amp; validateAttributes() methods.
    - Added proper validation for attribute with an array as value.
    - Updated tests to be easier to debug.
- **2.0.0** - (2019-12-29)

    - Re-arranged the code.
    - Now requiring PHP 7.2 or above.
    - Removed an unneeded exception and added a new one.
    - Renamed `setAttributes()` to `addAttributes()` and implemented the ability to merge attributes.
    - Renamed `build()` to `toHtml()` (more explicit).
    - Added the ability to set an array as the attribute's value (for the "style" attribute).
    - The name of the element is now being automatically trimmed to remove any space around.
    - Fixed the return type for methods that can return a null value.
    - `setContent()` now accepts integer and float values.
    - It's no longer required to pass the name of the element in the constructor when instantiating.
    - Added `setName()` &amp; `setOptions()` methods.
- **1.1.0** - (2019-05-05)

    - You can now pass an array of $options\[\] to the constructor when instantiating the HtmlElement class.
- **1.0.0** - (2019-05-04)

    - The library is fully functional and ready to use.

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

[](#contributing)

If you'd like to contribute, please fork the repository and make changes as you'd like. Be sure to follow the same coding style &amp; naming used in this library to produce a consistent code.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity69

Established project with proven stability

 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

Every ~147 days

Recently: every ~184 days

Total

6

Last Release

1831d ago

Major Versions

1.1.0 → 2.0.02019-12-29

2.0.1 → 3.0.02020-09-21

3.0.0 → 4.0.02021-05-12

PHP version history (3 changes)1.0.0PHP &gt;=7.0.0

2.0.0PHP ^7.2

4.0.0PHP ^7.4 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/9d57dc1e2de89690f5f7c75fa82af0a525cee76ddf5dd02ecbbe2652390f43b0?d=identicon)[Artyuum](/maintainers/Artyuum)

---

Top Contributors

[![artyuum](https://avatars.githubusercontent.com/u/17199757?v=4)](https://github.com/artyuum "artyuum (55 commits)")

---

Tags

htmlhtml-elementlibraryphp7php8htmlHTML5formhtml-builder

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/artyuum-html-element/health.svg)

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

###  Alternatives

[phpoffice/phpword

PHPWord - A pure PHP library for reading and writing word processing documents (OOXML, ODF, RTF, HTML, PDF)

7.5k34.7M186](/packages/phpoffice-phpword)[twig/string-extra

A Twig extension for Symfony String

21946.0M133](/packages/twig-string-extra)[twig/markdown-extra

A Twig extension for Markdown

12114.3M83](/packages/twig-markdown-extra)[laminas/laminas-view

Fast and type safe HTML templating library with a flexible plugin system supporting multistep template composition

7526.3M230](/packages/laminas-laminas-view)[twig/html-extra

A Twig extension for HTML

777.6M41](/packages/twig-html-extra)[laravie/html

HTML and Form Builders for the Laravel Framework

36184.6k4](/packages/laravie-html)

PHPackages © 2026

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