CSV File to Separate HTML Tables Based on Column Values - php

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

Related

How to place HTML tags in a CSV?

I have an excel sheet. In this excel sheet it contains Parts Number, Summary, Brand, Status. I would like to be able to import CSV data which contains text that already has html so I don’t have to apply all the formatting after import.
In this new csv, it should only contain 3 columns, Parts Number, Summary and html table. In this html table, it contains Parts Number, Summary, Brand, Status.
I have already created a table using php and it worked, now I am having difficulty trying to bring the table to csv.
Here is my code:
<?php
$file = fopen("Book1.csv","r");
$file2 = fopen("Book2.csv","w");
$data = [];
$description = '<table class="table">';
while($row = fgetcsv($file)) {
$data[] = $row; //Get all the data
}
if($data){
$n_columns = count($data[0]); //Get number of columns
}
$description .= '<table border="1">';
for ($col = 0; $col < $n_columns; $col++) {
$description .= '<tr>';
foreach ($data as $row_k => $row) {
if ($row_k == 0) {
$description .= '<th>';
} else {
$description .= '<td>';
}
$description .= $row[$col] ?? '';
if ($row_k == 0) {
$description .= '</th>';
} else {
$description .= '</td>';
}
}
$description .= '</tr>';
fputcsv($file2, $data); // line 50
}
$description .= '</table>';
fclose($file);
fclose($file2);
?>
I am desperate, any help is appreciated.
If I understood you correctly, this should accomplish the task. It uses 3 functions, array_to_csv, csv_to_array and build_table.
<?php
function csv_to_array($filename, $header_row=true)
{
$handle = fopen($filename, 'r');
if ($header_row === true)
$header = fgetcsv($handle);
$data = [];
while ($row = fgetcsv($handle)) {
if ($header_row)
$data[] = array_combine($header, $row);
else
$data[] = $row;
}
return $data;
}
function array_to_csv($data, $filename, $header_row=true)
{
$handle = fopen($filename, 'w');
if ($header_row == true) {
$header = array_keys($data[0]);
fputcsv($handle, $header);
}
foreach ($data as $line) {
fputcsv($handle, $line);
}
fclose($handle);
}
function transpose_array($array)
{
$headers = array_keys($array[0]);
$transposed = [];
foreach ($array as $row) {
foreach ($headers as $header) {
if (!isset($transposed[$header]))
$transposed[$header] = [];
$transposed[$header][] = $row[$header];
}
}
return $transposed;
}
function build_table($array)
{
$transposed = transpose_array($array);
$table = '<table><tbody>';
foreach ($transposed as $heading => $row) {
$table .= '<tr><th>' . $heading .'</th>';
foreach ($row as $element) {
$table .= '<td>' . $element . '</td>';
}
$table .= '</tr>';
}
$table .= '</tbody></table>';
return $table;
}
$book1 = csv_to_array('Book1.csv');
$book2 = [];
foreach ($book1 as $row) {
$key = $row['Parts Number'];
if (!isset($book2[$key])) {
$book2[$key] = [
'Parts Number' => $key,
'Summary' => $row['Summary']
];
}
$book2[$key]['rows'][] = $row;
}
foreach ($book2 as &$product) {
$product['html table'] = build_table($product['rows']);
unset($product['rows']);
}
unset($product);
$book2 = array_values($book2);
array_to_csv($book2, 'Book2.csv');
Book1.csv contains:
Parts Number,Summary,Brand,Status,Country
6SE1200-1EA70-1,SIMOVERT P 6,Siemens,Discontinued,Germany
6SE1200-1EA70-1,SIMOVERT P 6,Siemens,Discontinued,France
6SE1200-1EA70-1,SIMOVERT P 6,Siemens,In Stock,England
6SE3012-0BA00,SIMOVERT P M,Siemens,Discontinued,-
Book2.csv output:
"Parts Number",Summary,"html table"
6SE1200-1EA70-1,"SIMOVERT P 6","<table><tbody><tr><th>Parts Number</th><td>6SE1200-1EA70-1</td><td>6SE1200-1EA70-1</td><td>6SE1200-1EA70-1</td></tr><tr><th>Summary</th><td>SIMOVERT P 6</td><td>SIMOVERT P 6</td><td>SIMOVERT P 6</td></tr><tr><th>Brand</th><td>Siemens</td><td>Siemens</td><td>Siemens</td></tr><tr><th>Status</th><td>Discontinued</td><td>Discontinued</td><td>In Stock</td></tr><tr><th>Country</th><td>Germany</td><td>France</td><td>England</td></tr></tbody></table>"
6SE3012-0BA00,"SIMOVERT P M","<table><tbody><tr><th>Parts Number</th><td>6SE3012-0BA00</td></tr><tr><th>Summary</th><td>SIMOVERT P M</td></tr><tr><th>Brand</th><td>Siemens</td></tr><tr><th>Status</th><td>Discontinued</td></tr><tr><th>Country</th><td>-</td></tr></tbody></table>"

how to filter data from html table

This is a code i used to prase a data through html dom php and echo a data in table form
all data came in perfect table form. but i want to show only 5 out of all data echo in table.at last i used table to echo a content or data i want only to echo 5 data out of all showing out but i am not getting any idea to code this.. any one can help me to do this?
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.discoverhongkong.com/us/see-do/events-festivals/events-calendar/index.jsp');
$eventRowData = array();
class eventRecord
{
public $dates;
public $eventDescription;
}
;
foreach ($html->find('#event_table tr') as $eventItem) {
$eventDateArray = array();
$oneEventData = new eventRecord;
foreach ($eventItem->find('.date') as $eventDate) {
$oneDateData = array();
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($eventDate);
$dom->preserveWhiteSpace = true;
$hTwo = $dom->getElementsByTagName('div')->item(0);
foreach ($hTwo->childNodes as $dateElement) {
array_push($oneDateData, $dateElement->nodeValue);
}
//print_r ($oneDateData);
array_push($eventDateArray, $oneDateData);
}
//
$oneEventData->dates = $eventDateArray;
$eventData = null;
foreach ($eventItem->find('.event_name') as $eventName) {
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($eventName);
$dom->preserveWhiteSpace = true;
$baseLink = "http://www.discoverhongkong.com";
$img = $dom->getElementsByTagName('a')->item(0);
$relativeLink = $img->attributes->getNamedItem("href")->value;
$eventLink = $baseLink . $relativeLink;
$eventData = '<strong>' . $img->textContent . '</strong><br />';
$oneEventData->eventDescription = $eventData;
//echo $oneEventData->eventDescription;
}
array_push($eventRowData, $oneEventData);
}
$arr = array_values($eventRowData);
//Print_r ($eventRowData);
//echo "----------";
//echo $arr[0]->eventDescription;
//echo "----------";
echo '</br>';
echo '<h2>Events In HongKong</h2>';
echo '<table class="table-bordered">';
echo '<tr>';
echo '<th class="abc">EVENT NAME</th>';
echo '<th>START DATE</th>';
echo '<th>END DATE</th>';
echo '</tr>';
foreach ($arr as $xyz) {
//print_r ($xyz);
echo '<tr>';
echo '<td>';
echo ($xyz->eventDescription);
echo '</td>';
//$mydates = array_values($xyz->dates);
//print_r ($mydates);
foreach ($xyz->dates as $datevalue) {
//echo '<tr>';
echo '<td>';
foreach ($datevalue as $datevalueitem) {
echo $datevalueitem;
echo '/';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
Which of these loops is the one you want to restrict? Whichever one it is, the structure would be the same. Something like this:
$i = 0;
foreach ($collection as $item) {
$i++;
if ($i > 5) {
break;
}
// the rest of your loop code
}
So you're basically storing in $i (or whatever you want to call the variable) a count of how many times the loop has executed. After 5 times, you use break; to exit the loop, regardless of how many records remain.

PHP fgetcsv display specific columns only

I'm using the code below (from a previous post) to pull from an csv file but I'd like to just display specific columns. I've already tried to modify using other solutions with no avail. Any help would be much appriciated.
<?php
function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table width="400" border="1" bordercolor="#666666" cellspacing="0" cellpadding="2">';
//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);
}
?>
HEADER1 | HEADER2 | HEADER3
COLUMN1 | COLUMN2 | COLUMN3
COLUMN1 | COLUMN3 | COLUMN3
Summary: I just want to display 1&2
Assuming you dont want to display the second column, iterate through the numerically indexed array and exclude the ones you want, something like:
<?php
function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table width="400" border="1" bordercolor="#666666" cellspacing="0" cellpadding="2">';
//display header row if true
if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $k => $v) {
if ($k != 1) {
echo "<th>$vth>";
}
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $k => $v) {
if ($k != 1) {
echo "<td>$v</td>";
}
}
echo '</tr>';
}
echo '</table>';
fclose($handle);
}
?>

MySQL to HTML table in PHP not displaying all MySQL rows

if(mysql_num_rows($result) == 0)
{
exit;
}
else{
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
$columns = array_keys(reset($data));
echo '<table>';
echo '<table border="3">';
echo '<tr>';
foreach($columns as $column)
{
echo "<th>$column</th>";
}
echo '</tr>';
foreach($data as $row);
{
echo '<tr>';
foreach($columns as $column)
{
echo '<td>'.$row[$column].'</td>';
}
echo '</tr>';
}
echo '</table>';
}
I'm not an expert (obviously) with either MySQL or PHP, and I'm not sure what I've done wrong. It's only displaying the final row in the MySQL table. Is there something I'm missing?
I think you need to fill your row array like this:
$data = array();
$index = 0;
while($row = mysql_fetch_assoc($result))
{
$data[$index] = $row;
$index++;
}

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