2013-03-27 36 views
2
$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>'; 

我想刪除父事業部,並獲得只有下面的輸出如何使用PHP的DOMDocument

<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內容?

回答

2

嘗試使用此功能

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> 
+0

謝謝,它工作正常。 – Munib 2013-03-27 06:46:37