Skip to content

Instantly share code, notes, and snippets.

@Krzysiu
Created August 13, 2016 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Krzysiu/0606827f401d6fe75986496208b21e61 to your computer and use it in GitHub Desktop.
Save Krzysiu/0606827f401d6fe75986496208b21e61 to your computer and use it in GitHub Desktop.
Generate HTML tag from array of parameters. Support for valueless parameters and self-closing tag.
<?php
/*! Generate HTML tag
* @param string $tag tag name (like "a" for <a>)
* @param type $params array of parameters in the format property => value. If value is null (strict), add valueless property
* @param mixed $content if null, generate self-closing tag; if value is given, even empty, add content and close tag
* @return Generated HTML tag
* @ingroup html
* @version 2
*/
function htmlize($tag, $params = [], $content = null) {
$paramStr = '';
foreach ($params as $property => $value) {
if ($value === null) $paramStr .= " {$property}"; else {
if (is_bool($value)) $value = booltostr($value);
$paramStr .= sprintf(' %s="%s"', $property, htmlspecialchars($value));
}
}
$ret = sprintf('<%s%s>', $tag, $paramStr);
if ($content !== null) $ret .= sprintf('%s</%s>', $content, $tag);
return $ret;
}
<?php
echo htmlize('p'); // <p>
echo htmlize('input', ['checked' => null, 'class' => 'form-control']); // <input checked class="form-control">
echo htmlize('a', ['href' => 'http://example.com', 'target' => 'isevil'], 'foobar'); // <a href="http://example.com" target="isevil">foobar</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment