I need to convert a PHP array into HTML tag attributes, with spaces and quotes, this is an example:
JavaScript
x
$array=array(
'attr1'=>'value1',
'id'=>'example',
'name'=>'john',
'class'=>'normal'
);
This is the result I need to achieve:
JavaScript
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::
JavaScript
$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"