php DOMDocument: html to node tree
This function converts html into a node tree (<ul>
structure). However, every node is returned as a child node of the preceding node even if that node was a sibling of the current node.
$xml = '
<div>
<div>
<b></b>
</div>
<p></p>
</div>
';
function xml2array($xml,&$result = '') {
foreach($xml->children() as $name => $xmlchild) {
xml2array($xmlchild, $result);
}
$result = "<ul><li>".$xml->getName().$result."</li></ul>";
}
$result='';
$dd = xml2array(simplexml_load_string($xml), $result);
echo "<pre>";
print_r($result);
the above code returns this:
<ul>
<li>div
<ul>
<li>p
<ul>
<li>div
<ul>
<li>b</li>
</ul>
</li>
</ul>
</li>
开发者_Go百科</ul>
</li>
</ul>
you notice 'div' is now a child of 'p' even though they are siblings, and 'div' comes after 'p' unlike the orignal input.
this is how it should look:
<ul>
<li>div
<ul>
<li>div
<ul>b</ul>
</li>
<li>p</li>
</ul>
</li>
</ul>
Here you go, a non-broken function, with the call by reference removed because if you don't know exactly what they are, possibilities of obscure bugs occur (and you might know how/when to use them, the next coder might struggle, references are best used with a very clear reason or not at all):
<?php
$xml = '
<div>
<div>
<b></b>
</div>
<p></p>
</div>
';
function xml2ul($xml) {
$children = $xml->children();
if(empty($children)) return '';
$result = '<ul>';
foreach($xml->children() as $name => $xmlchild) {
$result .= '<li>'.$name.xml2ul($xmlchild).'</li>';
}
$result .= '</ul>';
return $result;
}
echo xml2ul(simplexml_load_string($xml), $result);
精彩评论