Skip to content

Instantly share code, notes, and snippets.

@lordspace
Created July 21, 2014 08:58
Show Gist options
  • Save lordspace/fcc733e7e2a53ef427c3 to your computer and use it in GitHub Desktop.
Save lordspace/fcc733e7e2a53ef427c3 to your computer and use it in GitHub Desktop.
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