2

我有一个复杂的 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 作为字符串

4

0 回答 0