使用DOMdocument替换HTML标记,同时保留嵌套标记

时间:2013-08-28 13:35:57

标签: php dom domdocument domxpath

我有一个复杂的HTML结构,但它的一部分看起来像这样

....
<div class="otherclass"> 
   <div class="myclass">
       <b>some HTML</b>
       ...
   </div>
   <div class="myclass">
       <b>some HTML</b>
       ...
   </div>
</div>
...

我想将其转换为

...
<div class="otherclass">
   <span>
       <b>some HTML</b>
       ...
   </span>
   <span>
       <b>some HTML</b>
       ...
   </span>
</div>
...

我目前拥有的是

$xpath = new DOMXpath($doc);
$elements = $xpath->query("//*/div[@class='myclass']");
foreach( $elements as $element) {

    $new = $doc->createElement('span', $element->nodeValue);
    $parent = $element->parentNode;
    $parent->removeChild($element);
    $parent->appendChild($new);

}

但是这会删除所有HTML内部:

...
<div class="otherclass">
   <span>some HTML...</span>
   <span>some HTML...</span>
</div>
...

我还将HTML作为字符串

0 个答案:

没有答案