如何用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.
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.
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 }
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 liketable#my-tableortable.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

