简体   繁体   English

使用PHP计算HTML表中的列

[英]Count columns in a HTML table with PHP

I have a basic string with holds a html table. 我有一个基本的字符串,包含一个html表。 The table looks like this: 该表如下所示:

<TR>
    <TD>asdf, dfg</TD><TD>0915</TD><TD>0945</TD><TD></TD><TD>15</TD><TD>45</TD><TD></TD><TD>1315</TD>
</TR>
<TR>
    <TD>asdf, dfg</TD><TD>0915</TD><TD>0945</TD><TD></TD><TD>15</TD><TD>45</TD><TD></TD><TD>1315</TD>
</TR>
<TR>
    <TD>asdf, dfg</TD><TD>0915</TD><TD>0945</TD><TD></TD><TD>15</TD><TD>45</TD><TD></TD><TD>1315</TD>
</TR>
<TR>
    <TD>asdf, dfg</TD><TD>0915</TD><TD>0945</TD><TD></TD><TD>15</TD><TD>45</TD><TD></TD><TD>1315</TD>
</TR>       

How would I use PHP to determine how many columns this table has? 我如何使用PHP来确定此表有多少列?

As others have mentioned, if you have guaranteed valid HTML, and the table is guaranteed to have equal length rows, you can use simple string manipulation. 正如其他人所提到的,如果你保证有效的HTML,并且保证表有相同的长度行,你可以使用简单的字符串操作。 Split the string on <tr> , then count the number of <td> in each piece: 拆分<tr>上的字符串,然后计算每件中<td>的数量:

function count_table_columns($html) {
    $html = strtolower($html);
    $rows = split('<tr>', $html);
    foreach($rows as $row) {
        if(!trim($row)) { continue; }
        return substr_count($row, '<td>');
    }
}

If there is the possibility of malformed HTML, use an HTML parser to parse the table, then iterate through the <tr> nodes, and count the subnodes of type <td> . 如果HTML格式错误,请使用HTML解析器解析表,然后遍历<tr>节点,并计算<td>类型的子节点。

Here's one HTML parser to consider: http://sourceforge.net/projects/simplehtmldom/ 这是一个要考虑的HTML解析器: http//sourceforge.net/projects/simplehtmldom/

Count <TD> 's with substr_count() . 使用substr_count()计算<TD> If your string contains more than one row, then count <TR> 's and divide total number of <TD> 's by number of <TR> 's. 如果您的字符串包含多行,则计算<TR>并将<TD>的总数除以<TR>的数量。

This is simplehtmldom code that basically gets the number of columns in the HTML table 这是simplehtmldom代码,基本上获取HTML表中的列数

$table = $html->find('table',0);

foreach($table->find('tr') as $tr)
               {
                   $c=0;
                   foreach($tr->find('td') as $td) $c++;    
                   if( $c>$largest OR !isset($largest) ) $largest = $c; 
               }

$largest will give you column count. $ maximum会给你列数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM