在PHP中提取和转储DOM节点(及其子节点)

时间:2011-10-08 18:46:47

标签: php wordpress dom

'我有以下场景,我已经花了好几个小时试图处理它:我正在开发一个Wordpress主题(因此PHP),我想检查一个帖子(HTML)的内容是否包含标记有一定的id / class。如果是这样,我想从内容中提取它并将其放在其他地方。 示例:假设Wordpress帖子的文本内容为

<?php
  /* $content actually comes from WP function get_the_content() */
  $content = '<p>some text and so forth that I don\'t care about...</p> <div class="the-wanted-element"><p>I WANT THIS DIV!!!</p></div>';
?>

那么我怎么能用类提取div(也可以给它一个ID),在模板的一个地方输出(带标签和所有),然后输出其余的(没有提取的标签,当然)在模板的另一个地方? 我已经尝试过DOMDocument类,p.i.t.a。对我来说,也许我太傻了。

1 个答案:

答案 0 :(得分:2)

尝试:

$content = '<p>some text and so forth that I don\'t care about...</p> <div class="the-wanted-element"><p>I WANT THIS DIV!!!</p></div>';

$dom = new DomDocument;
$dom->loadHtml($content);

$xpath = new DomXpath($dom);
$contents = '';
foreach ($xpath->query('//div[@class="the-wanted-element"]') as $node) {
  $contents = $dom->saveXml($node);
  break;
}

echo $contents;

如何获取剩余的xml / html:

$content = '<p>some text and so forth that I don\'t care about...</p> <div class="the-wanted-element"><p>I WANT THIS DIV!!!</p></div>';

$dom = new DomDocument;
$dom->loadHtml($content);

$xpath = new DomXpath($dom);
foreach ($xpath->query('//div[@class="the-wanted-element"]') as $node) {
  $node->parentNode->removeChild($node);
  break;
}

$contents = '';
foreach ($xpath->query('//body/*') as $node) {
    $contents .= $dom->saveXml($node);
}

echo $contents;