douruoshen1449 2015-11-25 19:41
浏览 54
已采纳

DOMXpath和PHP:如何在<ul>中包含一堆<li>

I have a html-document with this not-so-nice markup, without the 'ul':

<p>Lorem</p>
<p>Ipsum...</p>
<li class='item'>...</li>
<li class='item'>...</li>
<li class='item'>...</li>
<div>...</div>

I am now trying to "grab" all li-elements and wrap them inside an ul-list which I'd like to place in the same spot, using PHP and DOMXPath. I manage to find and "remove" the li-elements:

$elements =  $xpath->query('//li[@class="item"]');

$wrapper = $document->createElement('ul');
foreach($elements as $child) {
    $wrapper->appendChild($child);
}
  • 写回答

2条回答 默认 最新

  • dousi7579 2015-11-25 21:35
    关注

    Maybe you can get the parentNode of the first <li> and then use the insertBefore method:

    $html = <<<HTML
    <p>Lorem</p>
    <p>Ipsum...</p>
    <li class='item'>...</li>
    <li class='item'>...</li>
    <li class='item'>...</li>
    <div>...</div>
    HTML;
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    
    $xpath = new DOMXpath($doc);
    
    $elements = $xpath->query('//li[@class="item"]');
    
    $wrapper = $doc->createElement('ul');
    $elements->item(0)->parentNode->insertBefore(
        $wrapper, $elements->item(0)
    );
    
    foreach($elements as $child) {
        $wrapper->appendChild($child);
    }
    
    echo $doc->saveHTML();
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了