I have the following array. I need to create a function which builds HTML from such kind of arrays. I have tried with recursion but somewhere there is mistake in my logic. Please help...
$arr = array(
'div' => array
(
0 => "Sample text sample text sample text.",
1 => array(
'ul' => array
(
'li' => Array
(
0 => "li 0 text.",
1 => "li 1 text.",
2 => "li 2 text."
)
)
)
)
);
The desired HTML output is :
<pre>
<div>Sample text sample text sample text.</div>
<div>
<ul>
<li>li 0 text.</li>
<li>li 1 text.</li>
<li>li 2 text.</li>
</ul>
</div>
</pre>
I have created the following function :
echo parseHTML($arr, '<div>');
function parseHTML($arr, $parentKey) {
static $str = "";
foreach ($arr as $key => $value) {
if (is_array($value)) {
if (is_numeric($key)) {
parseHTML($value, $parentKey);
} else {
parseHTML($value, $key);
}
} else if (is_numeric($key)){
$str .= '<'.$parentKey.'>'.$value .'</' . $parentKey . '>';
} else {
$str .= '<'.$key.'>'.$value .'</' . $key . '>';
}
}
return $str;
}
I am getting the following output:
<div>Sample text sample text sample text.</div>
<li>li 0 text.</li>
<li>li 1 text.</li>
<li>li 2 text.</li>
pcan not containul, that would be invalid HTML.