Search code examples
phphtmldomhtml-parsingsimple-html-dom

Simple HTML Dom - parse only few columns from original table


I want to copy some table to my website, but only with few specific columns

Here is my code

<?php

require('simple_html_dom.php');
$html = file_get_html('http://pomorskifutbol.pl/liga.php?id=970');

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

foreach($table->find('tr') as $row) {
    // initialize array to store the cell data from each row
    $flight = array();
    foreach($row->find('td') as $cell) {
        // push the cell's text to the array
        $flight[] = $cell->plaintext;
    }
    $rowData[] = $flight;
}

echo '<table>';
foreach ($rowData as $row => $tr) {
    echo '<tr>'; 
    foreach ($tr as $td)
        echo '<td>' . $td .'</td>';
    echo '</tr>';
}
echo '</table>';
?>

whole table And this prints whole table, I want to get only few columns, for example only "M.", "Drużyna", "M", "PKT" How extract only this columns from this table?


Solution

  • You can change the entry:

    foreach($row->find('td') as $cell) {
    

    to

    foreach($row->find('td') as $columnNumber => $cell) {
    

    and make an if before the filling of the $flights array, e.g

    //somewhere in code
    $columnNumbers = [ 0, 2, 3,4, 7];
    
    // int the foreach loop
    if ( in_array( $columnNumber, $columnNumbers ) ) {
     $flight[] = $cell->plaintext;
    }
    

    PS. Powodzenia :)