php DOMDocument class: node tree

不问归期 提交于 2019-12-25 01:37:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!