Skip to content

Instantly share code, notes, and snippets.

@mejta
Last active November 15, 2019 13:57
Show Gist options
  • Select an option

  • Save mejta/0073bf450716863c3e5ecf532c583084 to your computer and use it in GitHub Desktop.

Select an option

Save mejta/0073bf450716863c3e5ecf532c583084 to your computer and use it in GitHub Desktop.
PHP helper functions for creating HTML tags
<?php
namespace HtmlHelpers;
function el(string $tag, array $atts = [], array $content = []) {
if (empty($content)) {
return '<' . join(' ', array_filter([$tag, at($atts)])) . ' />';
}
return '<' . join(' ', array_filter([$tag, at($atts)])) . '>' . join($content) . '</' . $tag . '>';
}
function at(array $atts = []) {
$atts = array_filter($atts);
return join(' ', array_map(function ($attribute, $value) {
if ($value === true) {
return $attribute;
}
if (is_int($value)) {
return $attribute . '=' . $value;
}
if (is_array($value) || is_object($value)) {
$value = json_encode($value);
}
return $attribute . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
}, array_keys($atts), array_values($atts)));
}
$html = el('html', [], [
el('head', [], [
el('title', [], ['Some example title']),
el('meta', [
'content-type' => 'text/html;charset=utf-8',
]),
]),
el('body', ['class' => 'body'], [
el('h1', [], ['Some example header']),
el('p', [], [
'Some example paragraph',
el('br'),
'Other line',
]),
]),
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment