我目前正在通过simple_html_dom解析表格的特定列。哪个工作正常。我现在想在该组之后添加一个额外的列,每行有一个计算公式。它与各种行号一起使用也很重要,因为每个表可能有不同的行数。
It should work like this:
<external htmt table parsed via simple_html_dom>< - should be added into the array ->
row(1) = column1 | column2 | column3 | column4 | do nothing this is header
row(2) = cell1 | cell2 | cell3 | cell4 | sum cell 2 to 4 of row(2)
row(n) = cell1 | cell2 | cell3 | cell4 | sum cell 2 to 4 of row(n)
当我回显$ td单元格时,我想到将Dom Document添加到代码中。
// cells of row
echo '<td>' . $td .'</td>';
// now new cell at the end of row
echo '<td>';
// now adding calculation via Dom
$file = $DOCUMENT_ROOT. 'URL';
$doc = new DOMDocument;
$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
// Sum Column 2 + 3 + 4 of row 2 (in this example, different below)
print $xpath->evaluate('(//table/tr[2]/td[2])+(//table/tr[2]/td[3])+(//table/tr[2]/td[4])');
// closing cell and row
echo ' mio $</td>';
echo '</tr>';
这实际上有效,但显然只有第2行。所以每一行现在都有第2行的总和。有没有办法以不同方式计算每一行?
这是目前的整个代码
// Table 6 - Contracts
$table6 = $html->find('table', 6);
$rowData1 = array();
$columnNumbers = [ 3, 4, 5, 6];
foreach($table6->find('tr') as $row) {
// initialize array to store the cell data from each row
$flight1 = array();
foreach($row->find('td') as $columnNumber => $cell) {
// push the cell's text to the array
if ( in_array( $columnNumber, $columnNumbers ) ) {
$flight1[] = $cell->plaintext;
}
}
foreach($row->find('th') as $columnNumber => $cell) {
// push the cell's text to the array
if ( in_array( $columnNumber, $columnNumbers ) ) {
$flight1[] = $cell->plaintext;
} }
$rowData1[] = $flight1;
}
foreach ($rowData1 as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '<td>';
// now adding calculation via Dom
$file = $DOCUMENT_ROOT. 'URL';
$doc = new DOMDocument;
@$doc->loadHTMLFile($file);
$xpath = new DOMXpath($doc);
// Sum Column 4 + 5 + 6 of row 2
print $xpath->evaluate('(//table[td/u/b/.="Contracts"]/tr[2]/td[4])+(//table[td/u/b/.="Contracts"]/tr[2]/td[5])+(//table[td/u/b/.="Contracts"]/tr[2]/td[6])');
// closing cell and row
echo ' mio $</td>';
echo '</tr>';
}
echo '</table>