Simple HTML Dom - parse only few columns from original table - php

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?

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 :)

Related

loop through html table and get tr, th and td in php with simple dom parser

I need to get a table with simple html dom parser, clean it (remove attr and spaces), then output it again.
My question is, how can i loop through with PHP and output the TH and TD in one sequence?
At the moment it will handle the TH as a TD but i like to have the TH set correctly.
<table>
<tbody>
<tr>
<th>Date1</th>
<th>Date2</th>
</tr>
<tr>
<td>01.01.2019</td>
<td>05.01.2019</td>
</tr>
</tbody>
</table>
require('simple_html_dom.php');
$html = file_get_html( "template.html" );
$table = $html->find('table', 0);
$rowData = array();
foreach($table->find('tr') as $row) {
$keeper = array();
foreach($row->find('td, th') as $cell) {
$keeper[] = $cell->plaintext;
}
$rowData[] = $keeper;
}
echo '<table">';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
I tried something with the foreach, but i think i need something else.
ty for your ideas.
greet;s
You can do it like this:
require('simple_html_dom.php');
$html = file_get_html( "template.html" );
$table = $html->find('table', 0);
$rowData = array();
foreach($table->find('tr') as $row) {
$keeper = array();
foreach($row->find('td, th') as $cell) {
$data = array();
$data['tag'] = $cell->tag; //stored Tag and Plain Text
$data['plaintext'] = $cell->plaintext;
$keeper[] = $data;
}
$rowData[] = $keeper;
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<'.$td['tag'].'>' . $td['plaintext'] .'</'.$td['tag'].'>'; // Tag used
echo '</tr>';
}
echo '</table>';
You would need to store the type of cells, it would be enough to store them at row level as they should all be the same. Then when you rebuild the rows, use this type as the cell type to create...
foreach($table->find('tr') as $row) {
$keeper = array();
foreach($row->find('td, th') as $cell) {
$keeper[] = $cell->plaintext;
}
// Type is the 2nd & 3rd chars of html - <th>content</th> gives th
// Store type and cell data as two elements of the rowData
$rowData[] = ["type" => substr($cell,1,2), "cells" => $keeper];
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
// Loop over the cells of the row
foreach ($tr["cells"] as $td)
// Output row type as the element type
echo "<$tr[type]>" . $td ."</$tr[type]>";
echo '</tr>';
}
echo '</table>';

Generate arrays dynamic

I have this part of code
$records = array();
$records["data"] = array();
foreach ($rows as $row) {//select from DB
$records["data"][] =array();//XXXX
foreach($this->t_data['columns'] as $column) {//columns for table
$records['data'][][]=$row[$column['name']];//THIS need to add into XXXX array
}
}
$records["draw"] = $sEcho;
return json_encode($records);
In try in many ways to add data into array. this code is from datatables.
This is wotking code, static
foreach ($tickete as $row) {
$records["data"][] = array(
'<input type="checkbox" name="idticket" value="' . $row['id'] . '">',
$row['name'],
$row['type'],
$row['state']
);
}
Format:
{"data":[
["ID1","Name","Type","State"],
["ID2","Name","Type","State"],
["ID3","Name","Type","State"],
["ID4","Name","Type","State"],
["ID5","Name","Type","State"]],"draw":2,"recordsTotal":50,"recordsFiltered":50}
Multiple solutions:
1) Temporary array, pushed at the end:
foreach ($rows as $row) {
$subArray = array();
foreach($this->t_data['columns'] as $column) {
$subArray[] = $row[$column['name']];
}
$records["data"][] = $subArray;
}
2) Using array index:
foreach ($rows as $row) {
$records["data"][] = array();
foreach($this->t_data['columns'] as $column) {
$records["data"][count($records["data"]) - 1][] = $row[$column['name']];
}
}
3) Reference to newly created array using index (useful only when you need to access it more often):
foreach ($rows as $row) {
$records["data"][] = array();
$subArray = &$records["data"][count($records["data"] - 1)];
foreach($this->t_data['columns'] as $column) {
$subArray[] = $row[$column['name']];
}
}

CSV File to Separate HTML Tables Based on Column Values

I have a csv file that is converted to an html table by php (with help from Joby Joseph here): Dynamically display a CSV file as an HTML table on a web page
However, I would like to put the data into separate tables and container divs based on the values in the first two columns. So if this is my csv data:
League,Team,Date,Opponent,Result
american,MIN,May 3,UTA,W
american,MIN,May 4,SEA,L
american,SAC,May 3,DAL,L
american,SAC,May 4,TOR,W
national,NYN,May 5,BAL,L
national,NYN,May 7,MIA,W
national,DET,May 6,DEN,L
national,DET,May 7,POR,L
There would be four tables created (MIN, SAC, NYN, and DET), and they would be put into container divs that I have already created, "american-container" for the first two and "national-container" for the second two. Ideally, each table would have two header rows--the team name and the column labels--and the date/opponent/result data. Following is Joby's solution that puts the csv into one table:
function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table>';
//display header row if true
if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
fclose($handle);
}
jj_readcsv('test.csv',true);
Thanks for any help.
This should work :
<?php
$csv = "League,Team,Date,Opponent,Result\namerican,MIN,May 3,UTA,W\namerican,MIN,May 4,SEA,L\namerican,SAC,May 3,DAL,L\namerican,SAC,May 4,TOR,W\nnational,NYN,May 5,BAL,L\nnational,NYN,May 7,MIA,W\nnational,DET,May 6,DEN,L\nnational,DET,May 7,POR,L";
$csv_array = explode("\n", $csv);
$tables = [];
foreach($csv_array as $key => $value) {
if ($key == 0) {
continue;
}
$line = explode(',', $value);
if (array_key_exists($line[1], $tables)) {
$tables[$line[1]][] = $line;
} else {
$tables[$line[1]] = [$line];
}
}
foreach ($tables as $key => $value) {
echo '<h1> ' .$key. ' </h1>'; // YOUR TITLE (Team)
echo "<table>";
echo '<tr>';
foreach (explode(',', $csv_array[0]) as $keyHeader => $valueHeader) {
if (in_array($keyHeader, [0, 1])) {
continue;
}
echo "<th>$valueHeader</th>";
}
echo '</tr>';
foreach ($value as $keyRow => $valueRow) {
echo '<tr>';
foreach ($valueRow as $keyValue => $valueValue) {
if (in_array($keyValue, [0, 1])) {
continue;
}
echo "<td>$valueValue</td>";
}
echo '</tr>';
}
echo '</table>';
}
Here is what i get :
Jsfiddle

Convert array to another array

I have one array that I am showing like this:
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
The second and fourth columns are always the name of the column. The result is something like:
Name: John Locke - NickName: Locke
Age: 20 - Adress: Ok
See the pattern?
How can I put these array in my database?
As my database table structure is:
ID - Name - NickName - Age - Adress
I don't have a clue how to do that with the array i'm using..
--UPDATE
$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) {
foreach($cell->find('span') as $e){
$e->innertext = '';
}
// push the cell's text to the array
$flight[] = $cell->plaintext;
}
$rowData[] = $flight;
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
echo '<td>' . $row . '</td>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
you can do that:
$insert = "";
foreach ($rowData as $row => $tr) {
$insert .= "('".$tr[0]."','".$tr[0]."','".$tr[0]."','".$tr[0]."'),";
}
$insert = substr($insert, 0, -1)
$sql = "Insert into YourTable values ".$insert;
As you already know what the array positions relate to, IE positions 0 through 3. You can simply iterate as you are doing now and compile a query instead.
Just drop this snippet into your code, ive knocked this up on the fly and its a bit hackish, probably a better way. Just look at what it does on your screen and see where if any it needs correcting.
$insert = '';
for ($i=0; $i<=3; $i++):
$insert .= "'" . $tr[$i] . "'";
if ($i !== 3):
$insert .= ',';
endif;
endfor;
echo $insert;
Once you are seeing what looks like a correct insert then you can (using safe methods) insert it into your database.

Building a Table of Data with an Array of Arrays

I have an Array of Arrays and Want to create a Tabular data layout. This is not the exact code, as how their generated is quite the cluster (Coming from COBOL interaction) but this should give me enough to make it work if someone can think of a clean way to code this.
array(
Array(847.0, 97010, 11)
Array(847.0, 97012, 10)
Array(847.1, 97010, 08)
Array(847.1, 97012, 14)
)
So I want to put these into a Table that looks something like
97010 97012
847.0 11 10
847.1 08 14
The first 2 elements of the arrays will always be the two axis and the 3rd the contents of the table.
Any Suggestions? thanks!
$table = array();
$columns = array();
// copy the array (x, y, value) into a table
// keeping track of the unique column names as we go
foreach ($dataSet as $point) {
// provided sample data used floats, ensure it is a string
$x = strval($point[0]);
$y = strval($point[1]);
$data = $point[2];
if (!isset($table[$x])) {
$table[$x] = array();
}
$table[$x][$y] = $data;
// quick and dirty style 'unique on insert'
$columns[$y] = true;
}
// switch the column names from title => true to just titles
$columns = array_flip($columns);
// Display the table
echo '<table>';
// Header row
echo '<tr>';
echo '<th> </th>';
foreach ($columns as $columnTitle) {
echo '<th>' . $columnTitle . '</th>';
}
echo '</tr>';
// Bulk of the table
foreach ($table as $rowTitle => $row) {
echo '<tr>';
echo '<th>' . $rowTitle . '</th>';
foreach ($columns as $columnTitle => $junk) {
if (isset($row[$columnTitle]) {
echo '<td>' . $row[$columnTitle] . '</td>';
} else {
// Handle sparse tables gracefully.
echo '<td> </td>';
}
}
echo '</tr>';
}
echo '</table>';
From what I understood:
$arr[847.0][97010] = '11';
$arr[847.0][97012] = '10';
$arr[847.1][97010] = '08';
$arr[847.1][97012] = '14';
And you may create a table:
$result = "<table>";
foreach($arr as $row_key => $row) {
$result .= "<tr>";
foreach($row as $column_key => $data) {
$result .= "<td>".$data."</td>";
}
$result .= "</tr>";
}
$result .= "</table>";
echo $result;

Categories