You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用simple_html_dom为解析后的表格每行添加不同单元格及公式

Got it, let's tackle this step by step—you've already got the table parsing working, so we'll build on that to add dynamic calculated columns while handling variable row counts.

Step 1: Parse the External Table into a Manipulable Array

First, let's formalize how to get that external table into a PHP array. This gives us full control to add columns later, even when the number of rows changes:

// Include the simple_html_dom library
require_once('simple_html_dom.php');

// Fetch your external HTML (replace with your URL or raw HTML string)
$html = file_get_html('your-external-table-source.html');

// Initialize an array to store the entire table data
$tableData = [];

// Target your specific table (adjust the selector if needed, e.g., 'table#sales-data')
$targetTable = $html->find('table', 0);

// Loop through each row to populate the array
foreach ($targetTable->find('tr') as $row) {
    $rowCells = [];
    // Grab both th (header) and td (data) cells
    foreach ($row->find('td, th') as $cell) {
        $rowCells[] = trim($cell->plaintext);
    }
    $tableData[] = $rowCells;
}

// Clean up the DOM object to free memory
$html->clear();
unset($html);

Now $tableData holds your entire table—index 0 is the header row, and all subsequent indexes are your data rows.

Step 2: Add Dynamic Calculated Columns (Skip Header)

Since each data row needs a unique formula, we'll use callback functions to define per-row logic. This approach stays flexible even if the number of rows grows or shrinks:

// Define calculation rules for each data row (index starts at 1, since 0 is the header)
// Key = row index, Value = callback that takes the row's data and returns the calculated value
$rowCalculations = [
    1 => function($row) { return (float)$row[1] + (float)$row[2]; }, // Row 1: Column 1 + Column 2
    2 => function($row) { return (float)$row[1] * 1.08; }, // Row 2: Column 1 * 8% tax
    3 => function($row) { return (float)$row[2] / (float)$row[3]; }, // Row 3: Column 2 / Column 3
    // Add more rules as needed for additional rows
];

// Add a header for our new calculated column
$tableData[0][] = 'Calculated Result';

// Loop through data rows (skip index 0, the header)
for ($i = 1; $i < count($tableData); $i++) {
    $currentRow = $tableData[$i];
    
    // Use the specific rule if it exists; fall back to a default calculation otherwise
    if (isset($rowCalculations[$i])) {
        $calculatedValue = $rowCalculations[$i]($currentRow);
    } else {
        // Default logic for unexpected rows (adjust this to fit your needs)
        $calculatedValue = (float)$currentRow[1] * (float)$currentRow[2];
    }
    
    // Add the formatted calculated value as a new column
    $tableData[$i][] = number_format($calculatedValue, 2); // Format to 2 decimal places
}
Step 3: Use the Modified Table Data

Once you've added the calculated columns, you can output the table back to HTML, or use the array for other purposes:

// Example: Render the modified table as HTML
echo '<table border="1" cellpadding="8">';
foreach ($tableData as $row) {
    echo '<tr>';
    foreach ($row as $cell) {
        echo '<td>' . htmlspecialchars($cell) . '</td>';
    }
    echo '</tr>';
}
echo '</table>';

Quick Notes to Avoid Headaches:

  • Selector Accuracy: Double-check your find('table', 0) selector—if there are multiple tables on the page, use a more specific selector like table#my-table or table.data-table.
  • Data Type Conversion: Always cast string values from HTML to numbers ((float)/(int)) before calculating, otherwise you'll get string concatenation instead of math.
  • Dynamic Row Handling: If rows are added dynamically and you can't predefine rules, you can base calculations on values in existing columns (e.g., "if row has 'Tax' in column 0, use this formula").

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:05:31