在PHP中没有外部标记的某个标记中提取Html内容

问题描述:

I'd like to retrieve html code in a certain tag. I know DomDocument enables to do it. However, If I want to extract the contents without the outer tag, how can it be achieved?

For example,

$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));

this will output,

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

I want it without the outer div tag. I tried the node value but it strips all the tags.

$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;

Any ideas?

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

例如, p>

  $ html  ='&lt; div&gt;&lt; span&gt; Hello world!&lt; / span&gt;&lt; br&gt;&lt; p&gt;其他一些文字&lt; / p&gt;&lt; / div&gt;';  
 $ doc = new DOMDocument; 
 $ doc-&gt; loadHTML($ html); 
echo $ doc-&gt; saveXML($ doc-&gt; getElementsByTagName('div') - &gt; item(0));  
  code>  pre> 
 
 

这将输出, p>

 &lt; div&gt; 
&lt; span&gt; Hello world!&lt;  / span&gt; 
&lt; br&gt; 
&lt; p&gt;其他一些文字&lt; / p&gt; 
&lt; / div&gt; 
  code>  pre> 
 
 

我希望它没有 外部div标签。 我尝试了节点值,但它删除了所有标签。 p>

  $ html ='&lt; div&gt;&lt; span&gt; Hello world!&lt; / span&gt;&lt; br&gt;  &lt; p&gt;其他一些文字&lt; / p&gt;&lt; / div&gt;';  
 $ doc = new DOMDocument; 
 $ doc-&gt; loadHTML($ html); 
 $ node = $ doc-&gt; getElementsByTagName('div') - &gt; item(0); 
echo $ node-  &gt; nodeValue; 
  code>  pre> 
 
 

任何想法? p> div>

All right, how about a PHP innerHTML implementation:

<?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; 
} 
?>