1

我想检索某个标签中的 html 代码。我知道 DomDocument 可以做到这一点。但是,如果我想提取没有外标签的内容,如何实现呢?

例如,

$html = '<div><span>Hello world!</span><br><p>some other text</p></div>';    
$doc = new DOMDocument;
$doc->loadHTML($html);
echo $doc->saveXML($doc->getElementsByTagName('div')->item(0));

这将输出,

<div>
    <span>Hello world!</span>
    <br>
    <p>some other text</p>
</div>

我想要它没有外部 div 标签。我尝试了节点值,但它剥离了所有标签。

$html = '<div><span>Hello world!</span><br><p>some other text</p></div>';    
$doc = new DOMDocument;
$doc->loadHTML($html);
$node = $doc->getElementsByTagName('div')->item(0);
echo $node->nodeValue;

有任何想法吗?

4

1 回答 1

4

好吧,PHP innerHTML 实现怎么样:

<?php 
$html = '<div><span>Hello world!</span><br><p>some other text</p></div>';    
$doc = new DOMDocument;
$doc->loadHTML($html);
$node = $doc->getElementsByTagName('div')->item(0);
echo DOMinnerHTML($node);

function DOMinnerHTML($element) 
{ 
    $innerHTML = ""; 
    $children = $element->childNodes; 
    foreach ($children as $child) 
    { 
        $tmp_dom = new DOMDocument(); 
        $tmp_dom->appendChild($tmp_dom->importNode($child, true)); 
        $innerHTML.=trim($tmp_dom->saveHTML()); 
    } 
    return $innerHTML; 
} 
?> 
于 2012-08-24T09:47:45.603 回答