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

图片转代码服务由CSDN问答提供 功能建议

我有一个带有这个不太好的标记的html文档,没有'ul':

 &lt; p&gt; Lorem&lt; / p&gt; 
&lt; p&gt; Ipsum ...&lt; / p&gt; 
&lt; li class ='item'&gt; ...&lt;  / li&gt; 
&lt; li class ='item'&gt; ...&lt; / li&gt; 
&lt; li class ='item'&gt; ...&lt; / li&gt; 
&lt; div&gt; ...&lt;  ; / div&gt; 
   
 
 

我现在正试图“抓住”所有li元素并将它们包装在ul-list中,我希望将其放入 相同的地方,使用PHP和DOMXPath。 我设法找到并“删除”li元素:

  $ elements = $ xpath-&gt; query('// li [@ class =“item”]'  ); 
 
 $ wrapper = $ document-&gt; createElement('ul'); 
foreach($ elements as $ child){
 $ wrapper-&gt; appendChild($ child); 
} 
 <  / code>  
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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条)

相关推荐 更多相似问题