Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Here is a PHP class that allows you to create HTML attributes from a php array. If you pass the second parameter the key will be prefixed with 'data-' prefix so they can be access via jQuery later.
Class HTML_Util {
/**
* Usage: HTML_Util::array2attribs();
* @param array $attributes
* @param bool $make_them_data will prefix each key with 'data-' prefix so it's acessible via $('#elem').data();
* @return string
* @see http://stackoverflow.com/questions/18081625/how-do-i-map-an-associative-array-to-html-element-attributes
*/
public static function array2attribs($attributes = array(), $make_them_data = 0) {
$pairs = array();
foreach ($attributes as $name => $value) {
if ($make_them_data) {
$name = 'data-' . $name; // prefix the keys with data- prefix so it's accessible later.
}
$name = htmlentities($name, ENT_QUOTES, 'UTF-8');
$value = htmlentities($value, ENT_QUOTES, 'UTF-8');
if (is_bool($value)) {
if ($value) {
$pairs[] = $name;
}
} else {
$pairs[] = sprintf('%s="%s"', $name, $value);
}
}
return join(' ', $pairs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.