XPath - 获取textcontent()和HTML

时间:2012-12-18 19:02:29

标签: xpath domdocument

假设我有以下HTML:

<div class="some-class">
     <p> some paragraph</p>
     <h2>a heading</h2>
</div>

我想抓住<div class='some-class'>中的所有内容,包括HTML。以下只抓取文字:

$descriptions = $xpath->query("//div[contains(@class, 'some-class')]");
foreach($descriptions as $description)
       print $description->textContent;

获取包含的HTML标记的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

使用此功能 - 我从未发现任何内置功能,但效果很好:

function getInnerHTML($node)
{
    $innerHTML = "";
    $children = $node->childNodes; 
    foreach ($children as $child) { 
        $tmp_doc = new DOMDocument(); 
        $tmp_doc->appendChild($tmp_doc->importNode($child,true));        
        $innerHTML .= $tmp_doc->saveHTML(); 
    } 
    return $innerHTML;
}

答案 1 :(得分:0)

我相信您希望检索outerXml - 请查看DOMDocument::saveXML。或者我误解了你 - 你只需要<div>元素及其属性轴的xml序列化吗?

修改我的意思是你想要:

<div class="some-class">
     <p> some paragraph</p>
     <h2>a heading</h2>
</div>

或只是

<div class="some-class" />

相关问题