PHP Simple HTML DOM Parser,在没有任何特定唯一输入的情况下从TAG中删除属性

时间:2014-05-26 14:09:44

标签: php dom

my input

<div id='makeme' class='testme'>
   <span id='whatspanID'>somthing</span>
   <p class='ptagclass'></p>
</div>

My expected output
<div>
   <span></span>
   <p></p>
</div>

要删除标记内的内容,我可以使用下面的代码段,但如何从标记中删除属性

$html = str_get_html($str);
foreach($html->find("text") as $ht) {
   $ht->innertext = "";
}
$html->save();

1 个答案:

答案 0 :(得分:0)

使用DOM和Xpath可以选择文本和属性节点。

$html = <<<'HTML'
<div id='makeme' class='testme'>
   <span id='whatspanID'>somthing</span>
   <p class='ptagclass'></p>
</div>
HTML;

$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXpath($dom);

$div = $xpath->evaluate('//div[@id="makeme"]')->item(0);
$nodes = $xpath->evaluate('.//text()|@*|.//*/@*', $div);
foreach ($nodes as $node) {
  if ($node instanceof DOMAttr) {
    $node->parentNode->removeAttributeNode($node);
  } else {
    $node->parentNode->removeChild($node);
  }
}
echo $dom->saveHtml($div);

输出:

<div>
<span></span><p></p>
</div>