2010-11-18 26 views
0

想象一下,你必須通過php產生的一些代碼:PHP - 訪問和執行數據「即時」?

<ul> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
</ul> 
<ul> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
</ul> 
(...) 

但會動態生成,在一個函數加載的代碼,並沒有直接進入到各節點(<li>在這種情況下)。所以在我的網站上,它看起來有點像一個包括:

<?php include("but not the file but code above generated by some engine"); ?> 

所有明確?這就是交易。

我想修改此代碼。所以在加載後,我希望每個<ul>元素都在<div>的內部,並增加ID。所以結束代碼將如下所示:

<div id="1"> 
    <ul> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
    </ul> 
</div> 

<div id="2"> 
    <ul> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
    <li><?php smth ?></li> 
    </ul> 
</div> 

(...) 

任何想法?我有我自己的概念,基於加載後添加<div>s加入for循環後剝離網站的代碼,但我相信有更優雅的方式?

+0

我一直假設到關於ob_xmlfilter,但我叫名字。但通常可以捕獲輸出,將其輸入到QueryPath或phpQuery中,然後在PHP中重新構造(類似jQuery)。不利的一面是,這將是一個可衡量的放緩,所以你應該有一個非常好的用例。 – mario 2010-11-18 22:46:30

回答

-1

使用javascript和jquery。

$(document).ready(function() { 
    var i = 1; 
    $("ul").each(function() { 
     $(this).wrap('<div id="' + i + '" />'); 
     i++; 
    }); 
}); 
+1

它會殺死整個佈局給殘疾JS的人。 – fomicz 2010-11-18 22:22:27

+0

他在'加載後'寫道。我認爲這意味着...在頁面離開服務器端並在瀏覽器中呈現之後。這當然意味着你必須使用javascript。 – 2010-11-22 15:13:56

-1

你可以使用reqular表達式來破解密碼進入<ul>塊,然後拼在一起與周圍div的重新組裝。

基本上,你會打破原來的字符串到數組中,然後逐步通過數組並重新制作字符串。每次你步驟,只需添加一個開頭div與一個遞增的id到開始和結束div到結束,然後添加新的<ul>到最後一個字符串返回。

1

首先,清理你的HTML。您需要關閉ul標籤</ul>,而不是用<ul>打開新標籤。其次,您不允許以數字開頭的id值,至少在HTML4中。

另外,我不知道你所說的

<?php include("but not the file but code above generated by some engine"); ?> 

的意思到底是什麼,我認爲你的意思是你是包括輸出HTML文件。這使事情有點棘手。您將需要打開輸出緩衝。然後你可以用捕獲的內容做一些DOMDocument的東西。

<?php 

ob_start(); // turn output buffering on 
include('your_file.php'); // include the contents of your_file -- contents go into the output buffer 
$text = ob_get_clean(); // put the contents of the output buffer into $text 

$dom = new DOMDocument(); // create a DOMDocument to work on 

$f = $dom->createDocumentFragment(); 
$f->appendXML($text); 
$dom->appendChild($f); // these three lines import $text into $dom 

$i = 0; 
while ($dom->childNodes->length > 0) { // loop through the elements from your file 
    $child = $dom->childNodes->item(0); // working with the first remaining element 
    $dom->removeChild($child); // remove them -- we'll reinsert relevant elements later 

    if ($child->nodeType === XML_ELEMENT_NODE) { // forget about non-element nodes (i.e. whitespace) 
     $div[$i] = $dom->createElement('div'); // create a new parent element 
     $div[$i]->appendChild($child); // stick the current ul into it 
     $div[$i]->setAttribute('id', 'd' . (++$i)); // give it an id like d1, d2, etc. 
    } 
} 

foreach ($div as $d) { 
    $dom->appendChild($d); // reinsert each div element into the DOMDocument 
} 

echo $dom->saveHTML(); // echo the processed content 

當然,目前最簡單的方法是改變包含的文件...