Created
August 13, 2016 19:01
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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