0

我正在寻找一种使用 PHP 执行以下操作的方法。

文件夹 /section/ 中有多个页面。红色.html、蓝色.html、绿色.html。并且在服务器的根目录下有一个 index.html 页面。

在这些页面中的每一个上,都有一个 id 为“list”的 div,其中包含一个带有列表项的 ul。如何在 /section/ 中的每个页面上检索此 div 中列表项的数量,并返回 index.html 页面上每个页面的数量。

为了更好地说明它:

每一页的结构:

<div id="list">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>

    red.html (33 list items within #list)
    blue.html (20 list items within #list)
    green.html (15 list items within #list)

    index.html:

    **Stats:**
    Red: <php here fetching the number from red.html>
    Blue: <php here fetching the number from blue.html>
    Green: <php here fetching the number from green.html>
4

2 回答 2

0

您可以在索引中执行以下操作,但必须使用 PHP,因此您需要将其重命名为 index.php。

$sections = new DirectoryIterator('/path/to/sections');
$stats = array();

foreach($sections as $file) {
  if(!$file->isDot() && $file->isFile()) {
     $name = $file->getName();
     $path = $file->getPathname();
     $key =  str_replace('.html', '', $name);

     // load the html
     $dom = new DOMDocument();
     $dom->loadHTML($path);

     // get the LI of the list via xpath query
     $xpath = new DOMXPath($dom);
     $elements = $xpath->query("//ul[@id='list']/li");

     // assign the stat
     $stats[$key] = $elements->length;

     // free up some memory
     unset($elements, $xpath, $dom);
  }
}

之后,您只需要迭代$stats并输出您的计数。所以像:

<dl>
<?php foreach($stats as $label => $count): ?>
  <dt><?php echo $label ?></dt>
  <dd><?php echo $count ?></dd>
<?php endforeach ?>
</dl>
于 2012-09-29T20:34:26.923 回答
0

好吧,你有一些选择。.html建议我们谈论的是静态 html 文件,所以让我们来处理它。

1.)因为它都是静态的,所以您需要打开这些文件并解析它们(手动或可能使用一些 3rd 方库,如果存在的话)。然后你只需输出结果。

2.) 将静态 html 文件转换为 php,将 html 列表转换为数组。在您的红色、蓝色和绿色文件中,您需要枚举这些数组并简单地输出它们以获得相同的效果。但是,在您的 index.php 中,您需要做的就是包含这些文件并直接从这些可用的数组中获取信息。我相信您知道如何获取数组的元素数量,对吧?

编辑:

根据评论中的要求,我将尝试向您展示一个示例。可能这里最简单的方法是使用第二个选项。而不是使用静态类型的 html 列表,而是创建 php 变量 - 数组 - 包含您的项目。如果您需要显示这些项目,只需循环此集合并根据需要回显。如果您需要获取数组中的元素数量,只需使用 php 函数count(...)

显示项目示例:

红色.php

$someArray = array("one", "two", "three");

foreach ($someArray as $i -> $value)
{
    echo '<li>'.$value'.<li>';
}

索引.php

include_once 'red.php';

echo 'Count of elements in red.php: '.count($someArray);

或者类似的东西,希望你明白。

于 2012-09-29T20:25:59.237 回答