yiisoft/html
yiisoft/html is a lightweight PHP HTML builder for generating safe, well-formed markup. Create tags, attributes, forms, and input elements with fluent helpers, automatic escaping, and convenient utilities—ideal for Yii and any PHP project needing clean HTML generation.
Installation Add the package via Composer:
composer require yiisoft/html
No additional configuration is required—it’s a standalone library.
First Use Case: Basic HTML Generation Import the core classes and start building HTML:
use Yiisoft\Html\Html;
use Yiisoft\Html\HtmlTag;
// Generate a simple link
$link = Html::tag('a', 'Click me', ['href' => '/example']);
echo $link; // Output: <a href="/example">Click me</a>
Key Entry Points
Html::tag(): Core method for creating HTML tags.Html::encode(): Safely escape dynamic content.Html::activeForm(): For form generation (if using Yii integration).Html::a(), Html::img(), etc.Where to Look First
Yiisoft\Html\Html for available helpers.$userId = 123;
$editLink = Html::a('Edit', ['/users/edit', 'id' => $userId]);
$div = Html::tag('div', [
Html::tag('h1', 'Title'),
Html::tag('p', 'Content'),
], ['class' => 'container']);
$img = Html::tag('img', null, ['src' => '/image.jpg', 'alt' => 'Image']);
If using in a Yii project, leverage Html::activeForm() for model binding:
use Yiisoft\Yii\Web\View;
$form = Html::activeForm(['model' => $user]);
echo $form->field($user, 'username')->textInput();
echo Html::submitButton('Save');
$form->end();
Always encode dynamic content to prevent XSS:
$userInput = '<script>alert("XSS")</script>';
$safeInput = Html::encode($userInput);
// Output: <script>alert("XSS")</script>
Use the [] syntax for attributes:
$button = Html::tag('button', 'Submit', [
'type' => 'submit',
'data' => ['action' => 'save', 'confirm' => 'Are you sure?'],
]);
Create a helper file (e.g., app/Helpers/html.php):
if (!function_exists('html_tag')) {
function html_tag(string $tag, ?string $content = null, array $options = []): string {
return \Yiisoft\Html\Html::tag($tag, $content, $options);
}
}
Then use it in Blade:
{!! html_tag('div', 'Hello', ['class' => 'alert']) !!}
Encapsulate complex HTML in closures or classes:
function card(string $title, string $content): string {
return Html::tag('div', [
Html::tag('h3', $title),
Html::tag('p', $content),
], ['class' => 'card']);
}
Html::encode() with Laravel’s e() or Blade’s {!! !!}:
// ❌ Wrong (double-encoded)
echo Html::encode(e($userInput));
// ✅ Correct
echo e(Html::encode($userInput));
Html::tag() expects a single string or array of tags for content. Passing raw HTML fragments may break rendering:
// ❌ May fail if $html contains unescaped tags
Html::tag('div', $html);
// ✅ Safer
Html::tag('div', Html::encode($html));
Html::activeForm()) assume Yii’s request/response objects. In Laravel, mock these or use standalone alternatives.var_dump() or dd() to verify tag structure before rendering:
$tag = Html::tag('div', 'Test');
var_dump($tag); // Debug the raw HTML
href vs. herf) will silently fail. Validate with:
$attributes = ['href' => '/test', 'herf' => '/fallback'];
$link = Html::tag('a', 'Link', $attributes);
// Only 'href' will render; 'herf' is ignored.
Html::encode() uses htmlspecialchars() with ENT_QUOTES and UTF-8. Override if needed:
$customEncoded = htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'ISO-8859-1');
function button(string $label, array $options = []): string {
return Html::tag('button', $label, $options);
}
onclick for security):
function sanitizeAttributes(array $attributes): array {
unset($attributes['onclick'], $attributes['onload']);
return $attributes;
}
$safeTag = Html::tag('div', null, sanitizeAttributes($attrs));
function laravelLink(string $title, string $url, array $attributes = []): string {
return Html::a($title, $url, $attributes);
}
$navbar = Html::tag('nav', [
Html::tag('ul', [
Html::tag('li', Html::a('Home', '/')),
Html::tag('li', Html::a('About', '/about')),
]),
]);
Html::tag():
// ❌ Inefficient
Html::tag('div', Html::encode($userInput));
// ✅ Efficient
$safeInput = Html::encode($userInput);
Html::tag('div', $safeInput);
{!! !!} for raw HTML output from Html::tag() to avoid Blade auto-escaping:
{!! Html::tag('div', 'Raw HTML') !!}
$img = Html::tag('img', null, [
'src' => asset('images/logo.png'),
'alt' => 'Logo',
]);
old() helper with Html::activeForm() for persistence:
echo Html::activeTextInput($user, 'email', ['value' => old('email')]);
How can I help you explore Laravel packages today?