Skip to content
Advertisement

Convert PHP array into HTML tag attributes separated by spaces

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

Advertisement

Answer

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"

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement