4

I need to convert a PHP array into HTML tag attributes, with spaces and quotes, this is an example:

$array=array(
    'attr1'=>'value1',
    'id'=>'example',
    'name'=>'john',
    'class'=>'normal'
);

This is the result I need to achieve:

attr1="value1" id="example" name="john" class="normal"

There is any PHP function to do it?

I am trying these:

  • http_build_query
  • array_walk
Rana Ghosh
  • 4,514
  • 5
  • 23
  • 40
stramin
  • 2,183
  • 3
  • 29
  • 58
  • 1
    Take a look at this:https://stackoverflow.com/questions/11427398/how-to-implode-array-with-key-and-value-without-foreach-in-php – JustBaron May 30 '17 at 13:58
  • 1
    Possible duplicate of [How to implode array with key and value without foreach in PHP](https://stackoverflow.com/questions/11427398/how-to-implode-array-with-key-and-value-without-foreach-in-php) – Kempeth May 30 '17 at 14:00

6 Answers6

8

You can also use this easy one line code, please follwo below code::

$array=array(
    'attr1'=>'value1',
    'id'=>'example',
    'name'=>'john',
    'class'=>'normal'
);
$data = str_replace("=", '="', http_build_query($array, null, '" ', PHP_QUERY_RFC3986)).'"';
echo $data;

Output

attr1="value1" id="example" name="john" class="normal"

Rana Ghosh
  • 4,514
  • 5
  • 23
  • 40
  • 1
    Be warned, attributes as 'xmlns'=>"http://www.w3.org/2000/svg" doesn't play very well. – Teson Jul 02 '18 at 07:47
  • Use `urldecode` around `http_build_query` as http_build_query automatically encodes characters for URL, otherwise href="mailto:email@address" will be translated to href="mailto%3Aemail%40address" – Prof Aug 23 '21 at 06:55
6

Use a foreach loop to get the value and key.

$array = array(
  'attr1'=>'value1',
  'id'=>'example',
  'name'=>'john',
  'class'=>'normal');

foreach ($array as $key => $value) {
  echo $key . '="' . htmlspecialchars($value) . '" ';
}

If you wanted to use a function, you could just make your own such as the following.

$array = array(
  'attr1'=>'value1',
  'id'=>'example',
  'name'=>'john',
  'class'=>'normal');

echo buildTag($array);

function buildTag ($array) {
  $tag = '';
  foreach ($array as $key => $value) {
    $tag .= $key . '="' . htmlspecialchars($value) . '" ';
  }
  return $tag;
}
jkeys
  • 431
  • 3
  • 10
  • of course there is the assumption that both keys and values are valid HTML attributes and values - also no escaping must be required (ex. a double quote in a value `"` would break things) – Paolo May 30 '17 at 14:18
  • Yes you're completely right, however, I was going under the assumptions which the user would be using this piece properly – jkeys May 30 '17 at 14:26
6

I use the following function:

function buildAttributes($attributes)
{
    if (empty($attributes))
        return '';
    if (!is_array($attributes))
        return $attributes;

    $attributePairs = [];
    foreach ($attributes as $key => $val)
    {
        if (is_int($key))
            $attributePairs[] = $val;
        else
        {
            $val = htmlspecialchars($val, ENT_QUOTES);
            $attributePairs[] = "{$key}=\"{$val}\"";
        }
    }

    return join(' ', $attributePairs);
}

It correctly escapes special html characters and supports boolean attributes (attributes without value). The following input:

[
    'name' => 'firstname',
    'value' => 'My Name',
    'required'
]

Will produce:

name="firstname" value="My Name" required
Dima L.
  • 3,443
  • 33
  • 30
2

You could also utilize array_map() in conjunction with array_keys() to build your $key=$value string.

Wrapped in array_filter() to remove empty items and ultimately use implode() to glue your items together.

$array = array(
    'attr1' => 'value1',
    'id'    => 'example',
    'name'  => 'john',
    'class' => 'normal',
    'c'     => null,
    'd'     => '',
    'e'     => '"abc"'
);

$attributes = implode( ' ', array_filter( array_map( function ( $key, $value ) {
    return $value ? $key . '="' . htmlspecialchars( $value ) . '"' : false;
}, array_keys( $array ), $array ) ) );


echo "<div " . $attributes . "></div>";

Result:

<div attr1="value1" id="example" name="john" class="normal" e="&quot;abc&quot;"></div>
wbq
  • 633
  • 4
  • 13
1

The shortest one-line function to do that would be:

function add_attributes($attributes){
      return urldecode(http_build_query(array_map(function($v){ return '"'.((string) $v).'"'; }, $attributes), '', ' '));
}

You can use it like this:

$array=array(
    'attr1'=>'value1',
    'id'=>'example',
    'name'=>'john',
    'class'=>'normal'
);

echo '<div '.add_attributes($array).'></div>';

will produce:

<div attr1="value1" id="example" name="john" class="normal"></div>
Bastien Ho
  • 777
  • 12
  • 23
0

You can use this function:

public static function arrayToStringTags( $array )
{
    $tags = '';

    if(!(is_array($array) && !empty($array)))
    {
        return $tags;
    }

    foreach($array as $key => $value)
    {
        $tags .= $key. '="'. $value. '" ';
    }

    return $tags;
}
alimatin
  • 1
  • 1