2011-01-06 118 views
7

說我有以下的HTML如何使用XPath和DOM替換php中的節點/元素?

$html = ' 
<div class="website"> 
    <div> 
     <div id="old_div"> 
      <p>some text</p> 
      <p>some text</p> 
      <p>some text</p> 
      <p>some text</p> 
      <div class="a class"> 
       <p>some text</p> 
       <p>some text</p> 
      </div> 
     </div> 
     <div id="another_div"></div> 
    </div> 
</div> 
'; 

而且我想用下面的更換#old_div

$replacement = '<div id="new_div">this is new</div>'; 

舉的最終結果:

$html = ' 
<div class="website"> 
     <div> 
      <div id="new_div">this is new</div> 
      <div id="another_div"></div> 
     </div> 
    </div> 
'; 

有一個簡單的剪切和粘貼功能使用PHP做到這一點?


最後的工作代碼感謝所有戈登的幫助:

<?php 

$html = <<< HTML 
<div class="website"> 
    <div> 
     <div id="old_div"> 
      <p>some text</p> 
      <p>some text</p> 
      <p>some text</p> 
      <p>some text</p> 
      <div class="a class"> 
       <p>some text</p> 
       <p>some text</p> 
      </div> 
     </div> 
     <div id="another_div"></div> 
    </div> 
</div> 
HTML; 

$dom = new DOMDocument; 
$dom->loadXml($html); // use loadHTML if it's invalid XHTML 

//create replacement 
$replacement = $dom->createDocumentFragment(); 
$replacement ->appendXML('<div id="new_div">this is new</div>'); 

//make replacement 
$xp = new DOMXPath($dom); 
$oldNode = $xp->query('//div[@id="old_div"]')->item(0); 
$oldNode->parentNode->replaceChild($replacement , $oldNode); 
//save html output 
$new_html = $dom->saveXml($dom->documentElement); 

echo $new_html; 

?> 
+1

可能重複的[使用DOMXPath替換節點,同時保持其位置...](http://stackoverflow.com/questions/640815/using-domxpath-to-replace-a-node-while-維護其位置) – Gordon 2011-01-06 11:36:40

+1

您可以使用** XPath來選擇**目標節點以**替換DOM方法**。反映標題。 – 2011-01-06 12:11:42

回答

11

由於在鏈接重複的答案是不是全面的,我舉個例子:

$dom = new DOMDocument; 
$dom->loadXml($html); // use loadHTML if its invalid (X)HTML 

// create the new element 
$newNode = $dom->createElement('div', 'this is new'); 
$newNode->setAttribute('id', 'new_div'); 

// fetch and replace the old element 
$oldNode = $dom->getElementById('old_div'); 
$oldNode->parentNode->replaceChild($newNode, $oldNode); 

// print xml 
echo $dom->saveXml($dom->documentElement); 

從技術上講,您不需要XPath。但是,可能發生的情況是,您的libxml版本無法對未驗證的文檔執行getElementByIdid attributes are special in XML)。在這種情況下,與

$xp = new DOMXPath($dom); 
$oldNode = $xp->query('//div[@id="old_div"]')->item(0); 

Demo on codepad


更換調用getElementById要創建子節點$newNode,而無需創建和一個附加的元素之一,你可以做

$newNode = $dom->createDocumentFragment(); 
$newNode->appendXML(' 
<div id="new_div"> 
    <p>some other text</p> 
    <p>some other text</p> 
    <p>some other text</p> 
    <p>some other text</p> 
</div> 
'); 
+0

非常感謝戈登,現在就試試吧! – Haroldo 2011-01-06 11:46:15

-7

使用jQuery隱藏()首先隱藏特定的div,然後使用append追加新的div

$('#div-id').remove(); 
$('$div-id').append(' <div id="new_div">this is new</div>');