php DOMDocument类:节点树

时间:2011-04-03 07:51:15

标签: php html html-parsing domdocument

我想将html语法转换为节点树(<ul>结构)。如何使用DOMDocument类执行此操作?

$html = '

   <div>
       <p>
           <a>
       </p>
  </div>

';



结果:

<ul>
   <li>
       div
        <ul>
            <li>
               p
                <ul> 
                    <li>a</li>
                </ul> 
           </li>
        </ul>
   </li>
</ul>

1 个答案:

答案 0 :(得分:0)

<?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);

输出

<ul>
    <li>
        div
        <ul>
            <li>
                p
                <ul>
                    <li>
                        a
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>