-1

我正在处理的一个网站已经有大约 140 个 HTML 文件,每个文件都包含一个不同的 HTML 表格。每个表有 10 到大约 400 行和 2 列。这是不符合标准的旧代码,目前我正在尝试使用该旧代码。

这是一个例子:

<TABLE BORDER=0>
  <TR><TD><FONT SIZE=1>Row 1 Col 1</TD><TD WIDTH+20><FONT SIZE=1>Row 1 Col 2</TD><TR>
<TR><TD><FONT SIZE=1>Row 2 Col 1</TD><TD WIDTH+20><FONT SIZE=1>Row 2 Col 2</TD><TR>
<TR><TD><FONT SIZE=1>Row 3 Col 1</TD><TD WIDTH+20><FONT SIZE=1>Row 3 Col 2</TD><TR>
...
</TABLE>

我试图在 PHP 中找到一种方法来计算表中有多少行,然后将这些行分成 4 个 div。所以如果我们有一个有 100 行的表。前 25 行将进入此 div:

<div class="span3"><table>{first 25 rows go here}</table></div>

等等...

<div class="span3"><table>{next 25 rows go here}</table></div>
<div class="span3"><table>{next 25 rows go here}</table></div>
<div class="span3"><table>{next 25 rows go here}</table></div>

直到最后我们得到类似的东西:

<div class="row-fluid">
  <div class="span3"><table>{first 25% rows go here}</table></div>
  <div class="span3"><table>{next 25% rows go here}</table></div>
  <div class="span3"><table>{next 25% rows go here}</table></div>
  <div class="span3"><table>{next 25% rows go here}</table></div>
</div>

所有这些都需要在不实际编辑现有表中的代码的情况下完成。有谁知道我会如何用 PHP 做到这一点?

4

3 回答 3

1

我会使用 DomDocument 模型,如下所示:

$dom = new domDocument;
@$dom->loadHTML($html);
$rows = $dom->getElementsByTagName('tr');
于 2013-07-08T12:14:50.993 回答
1

谢谢大家的提示。这就是我沿 DomDocument 路线回答问题的方式。

 <?php

  $dom = new DOMDocument();

  //load the html
  $html = $dom->loadHTMLFile($path.$filename);

  //discard white space 
  $dom->preserveWhiteSpace = false; 

  //the table by its tag name
  $tables = $dom->getElementsByTagName('table'); 

  //get all rows from the table
  $rows = $tables->item(0)->getElementsByTagName('tr'); 

$numberofrows = $tables->item(0)->getElementsByTagName('tr')->length;

$numberincolumn = ceil($numberofrows / 4);

  $counter = 0;
echo '<div class="row-fluid"><div class="span3"><table>';
  // loop over the table rows

  foreach ($rows as $row) 
  { 


    if ($counter > 0 && $counter % $numberincolumn == 0){
    echo '</table></div><div class="span3"><table>';    
    }



   // get each column by tag name
      $cols = $row->getElementsByTagName('td'); 
   // echo the values  
      echo "<tr><td style='padding-left:10px;'>".$cols->item(0)->nodeValue.'</td>'; 
      echo "<td>".$cols->item(1)->nodeValue.'</td></tr>'; 
      $counter++;
    } 
    echo "</table></div></div>";
*/
?>
于 2013-07-08T16:59:35.790 回答
0

尝试链接这个

$data = "<TABLE BORDER=0>
  <TR><TD><FONT SIZE=1>Row 1 Col 1</TD><TD WIDTH+20><FONT SIZE=1>Row 1 Col 2</TD><TR>
<TR><TD><FONT SIZE=1>Row 2 Col 1</TD><TD WIDTH+20><FONT SIZE=1>Row 2 Col 2</TD><TR>
<TR><TD><FONT SIZE=1>Row 3 Col 1</TD><TD WIDTH+20><FONT SIZE=1>Row 3 Col 2</TD><TR>
...
</TABLE>";
$data = array_shift($data); // first array (table) 
$rows = explode("<TR>",$data); // you will loose the <TR> so you will need to add the <TR> back on to the begining

$numrows = count($rows);
于 2013-07-08T11:49:57.673 回答