2011-10-08 57 views
3

我正在爲我的網站開發一個輕量級嵌入式內容編輯器。類似於CushyCMSSurrealCMS,我的頁面的'可編輯'元素用class="editable"定義。使用PHP在文檔中查找和替換具有給定類名稱的html元素內容

我想通過2個變量通過AJAX到PHP:

$page該文件被寫入到(例如, '/path/index.html'。)

$json JSON字符串:{"0":"First Content","1":"Second Content","2":"Third Content"}其中關鍵是所有具有class="editable"的元素的索引,並且該值是每個元素的innerHTML。

在PHP 5.3中,如何打開$page並查找/替換class="editable"元素?

$page = $_POST['page']; 
$json = $_POST['json']; 

$doc = new DOMDocument(); 
$doc = DOMDocument::loadHTMLFile($page); 

// Detect DOM elements with class="editable" & replace content with JSON data 

// Save changes to designated file 
$doc->saveHTMLFile($page); // Write to file eg, 'index.html' 

echo ('Success'); 
+0

什麼是你現在環路輸出?此外,我不會只是「回聲('成功')」,我會做如果(fwrite($ fp,$ html))echo'success'; – bozdoz

+0

感謝您的回聲提示!現在,我得到了'解析錯誤:語法錯誤,意外的')''在行foreach($ ret [$ i]){'。 – Josiah

+0

哦。是啊。這不是foreach語法。我會在下面給出答案。 – bozdoz

回答

2

您可以使用XPath追蹤DOM中的所有可編輯元素。

$xpath = new DOMXPath($doc); 
$entries = $xpath->query('//*[@class="editable"]'); 
$edits = json_decode($json, true); 
$num_edits = count($edits); 

for($i=0; $i<$num_edits; $i++) 
{ 
    $f = new DOMDocument(); 
    $edit = mb_convert_encoding($edits[$i], 'HTML-ENTITIES', "UTF-8"); 
    $f->loadHTML($edit); 
    $node = $f->documentElement->firstChild; 
    $entries->item($i)->nodeValue = ""; 
    foreach($node->childNodes as $child) { 
     $entries->item($i)->appendChild($doc->importNode($child, true)); 
    } 
} 

這又是你的原代碼方面:

$page = $_POST['page']; 
$json = $_POST['json']; 

$doc = new DOMDocument(); 
$doc = DOMDocument::loadHTMLFile($page); 

// Detect DOM elements with class="editable" & replace content with JSON data 
$xpath = new DOMXPath($doc); 
$entries = $xpath->query('//*[@class="editable"]'); 
$edits = json_decode($json, true); 
$num_edits = count($edits); 

for($i=0; $i<$num_edits; $i++) 
{ 
    $f = new DOMDocument(); 
    $edit = mb_convert_encoding($edits[$i], 'HTML-ENTITIES', "UTF-8"); 
    $f->loadHTML($edit); 
    $node = $f->documentElement->firstChild; 
    $entries->item($i)->nodeValue = ""; 
    foreach($node->childNodes as $child) { 
     $entries->item($i)->appendChild($doc->importNode($child, true)); 
    } 
} 

// Save changes to designated file 
$doc->saveHTMLFile($page); // Write to file eg, 'index.html' 

echo ('Success'); 
+0

完美!!!!!我必須等待20小時才能獲得賞金 - 非常感謝! – Josiah

+0

'nodeValue'似乎正在將我的html標籤轉換爲純文本。無論如何要保持它作爲innerHTML? – Josiah

+0

@Josiah:由於最近發現舊代碼只處理格式良好的XHTML,但是HTML,我改進了'for'循環。現在它應該沒有任何問題。 – Herbert

0

如果for循環提供索引,則不應該需要foreach循環。試試這個:

// Write JSON content to class="editable" elements 
for ($i = 0; $i < $ret->length; $i++) { 
     echo $data[$i]; 
} 
0

您可以使用QueryPath,一個PHP庫,用於操縱XML和HTML。像jQuery for PHP一樣。

從他們的網站:

QueryPath is a PHP library for manipulating XML and HTML. It is designed to work not only with local files, but also with web services and database resources. It implements much of the jQuery interface, but it is heavily tuned for server-side use.

相關問題