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
2

6 Answers 6

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"

Sign up to request clarification or add additional context in comments.

2 Comments

Be warned, attributes as 'xmlns'=>"w3.org/2000/svg" doesn't play very well.
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"
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;
}

2 Comments

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)
Yes you're completely right, however, I was going under the assumptions which the user would be using this piece properly
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

Comments

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>

Comments

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>

Comments

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;
}

2 Comments

Add some text to explain the answer which is pure code.
To be honest, most other answers do not provide any explanation either...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.