Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Last active January 8, 2024 04:14
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mcaskill/0177f151e39b94ee2629f06d72c4b65b to your computer and use it in GitHub Desktop.
Save mcaskill/0177f151e39b94ee2629f06d72c4b65b to your computer and use it in GitHub Desktop.
PHP / WordPress : Generate a string of HTML attributes

💀 html_build_attributes

This gist has been deprecated and moved to a repository

(PHP 5 >= 5.4)
html_build_attributes — Generate a string of HTML attributes.

Description

string html_build_attributes( array $attr [, callable $callback = null ] )

Generate a string of HTML attributes from the associative array provided.

Parameters

  • attr — Associative array, or object containing properties, representing attribute names and values.
    If attr is an object, then only public properties will be incorporated into the result.
    If a value is an array, its values will be concatenated and delimited with a space.
    Values that cannot be converted into strings will be ignored. If the value is Stringable, Arrayble, or a Closure, attempts will be made to parse as a string.
  • callback — Callback function for escaping the values for the HTML attributes.
    If no sanitizer is provided, htmlspecialchars() is used;
    If using WordPress, the esc_attr() function is used.

Return Values

Returns a string of HTML attributes.

Installation

With Composer

$ composer require mcaskill/php-html-build-attributes

Without Composer

Why are you not using composer? Download Function.HTML-Build-Attributes.php from the gist and save the file into your project path somewhere.

{
"name": "mcaskill/php-html-build-attributes",
"description": "Generate a string of HTML attributes.",
"license": "MIT",
"authors": [
{
"name": "Chauncey McAskill",
"email": "chauncey@mcaskill.ca",
"homepage": "https://github.com/mcaskill"
}
],
"keywords": [
"function",
"wordpress"
],
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"require": {
"php": ">=5.4.0"
},
"autoload": {
"files": [ "Function.HTML-Build-Attributes.php" ]
}
}
<?php
if (!function_exists('html_build_attributes')) {
/**
* Generate a string of HTML attributes
*
* @param array $attr Associative array of attribute names and values.
* @param callable|null $callback Callback function to escape values for HTML attributes.
* Defaults to `htmlspecialchars()`.
* @return string Returns a string of HTML attributes.
*/
function html_build_attributes(array $attr, callable $callback = null)
{
if (!count($attr)) {
return '';
}
$html = array_map(
function ($val, $key) use ($callback) {
if (is_bool($val)) {
return ($val ? $key : '');
} elseif (isset($val)) {
if ($val instanceof Closure) {
$val = $val();
} elseif ($val instanceof JsonSerializable) {
$val = json_encode(
$val->jsonSerialize(),
(JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)
);
} elseif (is_callable([ $val, 'toArray' ])) {
$val = $val->toArray();
} elseif (is_callable([ $val, '__toString' ])) {
$val = strval($val);
}
if (is_array($val)) {
if (function_exists('is_blank')) {
$filter = function ($var) {
return !is_blank($var);
};
} else {
$filter = function ($var) {
return !empty($var) || is_numeric($var);
};
}
$val = implode(' ', array_filter($val, $filter));
}
if (is_callable($callback)) {
$val = call_user_func($callback, $val);
} elseif (function_exists('esc_attr')) {
$val = esc_attr($val);
} else {
$val = htmlspecialchars($val, ENT_QUOTES);
}
if (is_string($val)) {
return sprintf('%1$s="%2$s"', $key, $val);
}
}
},
$attr,
array_keys($attr)
);
return implode(' ', $html);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment