在PHP中没有外部标签的情况下提取某个标签中的Html内容 [英] Extract Html Contents in a Certain Tag without the Outer Tag in PHP
本文介绍了在PHP中没有外部标签的情况下提取某个标签中的Html内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检索某个标签中的html代码。我知道DomDocument能够做到这一点。但是,如果我想提取没有外部标签的内容,怎么能实现?
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>
我不需要外部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?
推荐答案
好的,如何实现一个PHP innerHTML实现:
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;
}
?>
这篇关于在PHP中没有外部标签的情况下提取某个标签中的Html内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文