PHP - “动态”访问和修改数据?

时间:2010-11-18 22:11:30

标签: 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 for循环后剥离网站的代码,但我相信有更优雅的方式?

3 个答案:

答案 0 :(得分: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

当然,到目前为止,最简单的解决方案是更改包含的文件......

答案 1 :(得分:-1)

使用javascript和jquery。

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

答案 2 :(得分:-1)

您可以使用reqular表达式将代码分解为<ul>的块,然后将div与div围绕它们重新组合。

基本上,您将原始字符串分解为数组,然后逐步执行数组并重新生成字符串。每次执行步骤时,只需在开头添加一个带有递增id的开始div,然后将div结尾添加到结尾,然后将新<ul>添加到最终字符串中以返回。