$html_string = '<div class="quote" post_id="57"
style="border:1px solid #000;padding:15px;margin:15px;"
user_id="1" user_name="david_cameron"><strong><span
style="font-size:200%;">My Name is Rashid Farooq</span></strong></div>';
我想删除 Parent Div 并只获得以下输出
<strong><span style="font-size:200%;">My Name is David Cameron</span></strong>
我试过了
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = $dom->getElementsByTagName('div');
$innerHTML_contents = $divs->item(0)->textContent
echo $innerHTML_contents
但它给了我唯一的“我的名字是大卫·卡梅伦”并去掉了所有标签。 如何只删除父 div 并获取 div 中的所有其他 html 内容?
最佳答案
尝试使用这个功能
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;
}
喜欢
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = $dom->getElementsByTagName('div');
$innerHTML_contents = DOMinnerHTML($divs->item(0));
echo $innerHTML_contents
输出
<strong><span style="font-size:200%;">My Name is Rashid Farooq</span></strong>
关于php - 如何使用 PHP DOMDocument 删除父 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15652810/