问题
I want to convert html syntax into a node tree (<ul>
structure). How do I do this using the DOMDocument class?
$html = '
<div>
<p>
<a>
</p>
</div>
';
result:
<ul>
<li>
div
<ul>
<li>
p
<ul>
<li>a</li>
</ul>
</li>
</ul>
</li>
</ul>
回答1:
<?php
$xml = '<div>
<p>
<a>#</a>
</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);
output
<ul>
<li>
div
<ul>
<li>
p
<ul>
<li>
a
</li>
</ul>
</li>
</ul>
</li>
</ul>
来源:https://stackoverflow.com/questions/5528321/php-domdocument-class-node-tree