I'm very new to PHP and have been experimenting with combining with css to turn a CSV file into a table on my site. I wondered if you could select to show just a range of rows from a CSV file, e.g. rows 5 to 20, and found the code below to show certain columns.
Is there a simple way to switch this to show selected rows instead?
<?php
$row = 1;
if (($handle = fopen("donors.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<td style="border-top: 1px solid rgb(111,180,224); border-left: 1px solid rgb(111,180,224); border-bottom: 1px solid rgb(111,180,224);" align="left" bgcolor="#0066cc" height="36" valign="middle" ><b><font color="#ffffff" size="2"> '.$value.' </font></b></td>';
}else{
echo '<td style=" border-bottom: 1px solid rgb(111,180,224);" sdval="9" sdnum="1040;" align="left" bgcolor="#ffffff" height="25" valign="middle"><font color="#000000" size="2"> '.$value.' </font></td>';
}
}
if ($row == 1) {
echo '</tr>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
echo '</center>';
fclose($handle);
}
?>
I'm not really sure to undestand what you want to display.
But on the test website i added a table which diplay a range of lines.
Here is the code of this table:
echo "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>
<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\">";
$file = '/var/www/test/test.csv';
echo "<h1><b>Lines X to Y</b></h1>";
echo "<table>"; //create the html table
$x=2; //define the first line to display
$y=4; //define the last line to display
$line_counter=0;
foreach ($lines as $line) { //loop to fill your table with csv data
if($x<=$line_counter && $line_counter<=$y)
{
$expl = explode(",", $line); //explode each line on "," to create the rows
echo "<tr>"; //create each line of your table
$c=0;
while ($c<=26) { //loop to extract rows 5 to 20
if(($c % 2) == 1){ //odd rows
echo "<td class=\"odd\">".$expl[$c]."</td>";
}
elseif(($c == 0)){
echo "<td class=\"even\">".$expl[$c]."</td>";
}
else{
echo "<td class=\"even\">".$expl[$c]."</td>"; //even rows
}
$c++;
}
echo "</tr>";
$x++;
}
$line_counter++;
}
echo "</table>";
echo "<h1><b>content of the file</b></h1>";
foreach ($lines as $line) { //loop to fill your table with csv data
echo "$line<br/>" ;
}
The CSS is always in a separate file, and is the same as my first answer.
Select a range of rows:
i adapted this code from an old project, but it should work.
<?php
echo "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"/>
<link rel=\"stylesheet\" type=\"text/css\" href=\"test.css\">";
$file = '/volume1/web/Print data.csv';
$lines = file($file);
if (file_exists($file)){
//echo "$file exists<br/>";
echo "<table>"; //create the html table
foreach ($lines as $line) { //loop to fill your table with csv data
$expl = explode(",", $line); //explode each line on "," to create the rows
echo "<tr>"; //create each line of your table
$c=5;
while ($c<=20) { //loop to extract rows 5 to 20
if(($c % 2) == 1){ //odd rows
echo "<td class=\"odd\">".$expl[$c]."</td>";
}
else{
echo "<td class=\"even\">".$expl[$c]."</td>"; //even rows
}
$c++;
}
echo "</tr>";
}
echo "</table>";
}
else{
echo "file is not here: $file";
}
?>
For the css:
you should use an external .cssfile with this code
.odd {
border-top: 1px solid rgb(111, 180, 224);
border-left: 1px solid rgb(111, 180, 224);
border-bottom: 1px solid rgb(111, 180, 224);
background:#0066cc;
color:white;
font-weight:bold;
font-size:12px;
}
.even {
border-bottom: 1px solid rgb(111, 180, 224);
background: #ffffff;
color:#000000;
font-size:12px;
}
To check this css you can see this jsfiddle
I hope it will help you.
Edit
Fixed some missing ;. Added an picture of the result
1) Fetch your CSV file to an array with the below function (source: jaywilliams # GIST)
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
2) Iterate over the desired range of rows
$data = csv_to_array($file,$delimiter);
echo "your table header stuff"; //<table> ...
//first row numbered as 1
$from_row = 2; //second
$to_row = 50;
//first row numbered as 0
for($i = from_row-1; $i< $to_row-1; $i++)
{
echo "<tr>"; //start row
//now, every row of the CSV file is an array and consists of fileds=>values
//so now you are dealing with columns
foreach($data[$i] as $key=>$value
{
echo "<td>" . $value . "</td>";
}
echo "</tr>"; //end row
}
echo "your table footer stuff"; //</table> ...
From here, I guess you can do whatever your want, using CSS to style the tables. What is important, if you want the table header, you can feed the function with a CSV file with col names saved in first row.
Related
I am trying to get a table view from DB values in a specific pattern.
It should look like this:
Plan View
In the DB I have added row/col values to assign the "cell names" to a specific cell:
DB table
Using this code:
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
$data = $pdo->query("SELECT row, col, number FROM stalls ORDER BY row ASC, col ASC")->fetchAll();
echo'<table style="width:100%;">';
foreach ($data as $entry)
{
if($entry['row'] > 0)
{
for($r=0;$r<=$maxrow;$r++)
{
if($r == $entry['row'])
{
echo '<tr style="border: 1px solid black;">';
for($c=1;$c<=$maxcol;$c++)
{
if($c == $entry['col'])
{
echo '<td style="border: 1px solid black;">row: '. $r . ' - col: ' . $c . ' - value: ' . $entry['number'] .'</td>';
}
else
{
echo '<td style="border: 1px solid black;"></td>';
}
}
echo '</tr>';
}
}
}
}
echo '</table>';
I can only get this view:
Shifted rows
How would I get the values of "row 1" to be shown in row 1, without the "shift"?
Thank you very much for your help!
You could try something like - note this is untested code:
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
$oldRow = 0; // init row counter
$arr = array_fill( 0, $maxcol, " " );
$tmp = "";
echo'<table style="width:100%;">';
foreach ($data as $entry) {
// get the data
$row = $entry['row'];
$col = $entry['col'];
$nbr = $entry['number'];
// is the row number different and not the first entry
if( $oldRow != $entry['row'] && $oldRow != 0 ) {
//--- convert to html type string
$tmp = implode( "</td><td>", $arr );
//--- show html
echo'<tr><td>".$tmp."</td></tr>";
//--- reset temp values
$arr = array_fill( 0, $maxcol, " " );
$oldRow = $entry['row']; // set new row number
}
$arr[$row][$col] = $nbr;
}
//--- convert to html type string for last entry processed
$tmp = implode( "</td><td>", $arr );
//--- show html
echo'<tr><td>".$tmp."</td></tr>";
echo "</table>";
Finally, not very nice, but it works for me...
// get max rows
$maxrow = getResult($pdo, "SELECT MAX(row) AS maxrow FROM stalls")["maxrow"];
// get max cols
$maxcol = getResult($pdo, "SELECT MAX(col) AS maxcol FROM stalls")["maxcol"];
// get rows and number of cols in row
$rowmeta = $pdo->query("SELECT row, COUNT(*) as count FROM stalls WHERE row <> 0 GROUP BY row ORDER BY row ASC")->fetchAll(PDO::FETCH_ASSOC);
// get rest of stuff
$data = $pdo->query("SELECT row, col, number FROM stalls ORDER BY row ASC, col ASC")->fetchAll(PDO::FETCH_ASSOC);
echo'<table style="table-layout: fixed; width:100%;">';
// iterate trough rows from meta
foreach($rowmeta as $rowmeta_row)
{
echo '<tr style="width: calc(100%/'.$maxcol.');border: 1px solid black;">';
// get data part
foreach($data as $d)
{
// check if we're still in same row as data
if($rowmeta_row["row"] == $d['row'])
{
// move left trough cols
for($c=1;$c<=$maxcol;$c++)
{
// check if we're in the right col and it is not an isle
if($c == $d['col'] && $d['number'] != 'isle')
{
echo '<td style="border: 1px solid black;">row: '. $d['row'] . ' - col: ' . $d['col'] . ' - value: ' . $d['number'] .'</td>';
}
// still in right col, but isle
if($c == $d['col'] && $d['number'] == 'isle')
{
echo '<td style="border: 1px solid black;">leer</td>';
}
}
}
}
echo '</tr>';
}
I need to create a table whose first column is populated from subdirectory names inside a directory and rest are from a CSV file. This have to be a dynamic table and table headers have to be added from the code. What's wrong with my code?
I am an absolute beginner. So, please ignore my stupidity.
$dir = 'D:\workspace';
$dirlist = preg_grep('/^([^.])/', scandir($dir));
$row = 1;
if (($handle = fopen("D:\workspace\demo\database.csv", "r")) !== FALSE) {
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
foreach ($dirlist as $rowdirectory)
{
echo '<td>' . $rowdirectory . '</td>';
echo '<td>'.$value.'</td>';
}
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
<?php
#------------------------------------------Function for Reading Directory-------------------------------------------
function readdirectory($dir)
{
$dirlist = preg_grep('/^([^.])/', scandir($dir)); // for all(./../anything that
starts with .)
//$dirlist = preg_grep('/[^.]/', scandir($dir)); //only . & ..
//$dirlist =preg_grep('/^[(^.)]/', scandir($dir));//only files that starts with .
return $dirlist;
}
#------------------------------------------Function for Reading CSV file-------------------------------------------
function readcsvfile($source)
{
$handle = fopen($source, "r");
$filecontent = null;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$filecontent[] = $data;
}
fclose($handle);
return $filecontent;
}
$filecontent= readcsvfile("D:\workspace\demo\database2.csv");
#-------------------Directory Function calling, header array cration and other declaration------------------------------------
$conf_prefix= "../";
$conf_suffix="index.php";
$headerarray= $filecontent[0];
#var_dump($headerarray);
$headersize= count($headerarray);
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
$dir = 'D:\workspace';
$dirlist= readdirectory($dir);
#------------------------------------------Creating 1st row/Header row of Table-------------------------------------------
echo '<tr>';
for($a=0; $a<$headersize;$a++)
{
echo '<td>'.$headerarray[$a].'</td>';
}
echo '</tr>';
#-----------------------------Creating Table elements by comparing both directory arrays and CSV file array-------------------------------------------
foreach ($dirlist as $rowdirectory)
{
foreach ($filecontent as $value) {
$num = count($value);
if ($rowdirectory== $value[0])
{
$link= $conf_prefix. $rowdirectory."/".$conf_suffix;
echo '<tr>';
echo '<td> ' . $rowdirectory . ' </td>';
for( $c=1; $c < $num; $c++) {// loop for csv file
{
echo '<td>'.$value[$c].'</td>';//else print "value"
}
}
echo '</tr>';
}
}
}
?>
i would like to place the values of row 1 from my csv file within the td as in the example:
<td data-label="Jaar">2014</td>
Where in this example the word "Jaar" is cel a1 in my csv file.
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
} else {
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
print_r($data[$c]);
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th scope="col">'.$value.'</th>';
}else{
echo '<td data-label=".In here is want to place the values of row 1 or 2 or 3.">'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
In the php code the second line of the csv file is parsed as td, but i want to place the value of a1 in the first td data-label and the value of b1 into the second td data-label. Can anyone give me a hint.
csv file example:
aaaa;bbbb;cccc
1111;2222;3333
11;22;33
Save row 1 in a variable:
if ($row == 1) {
echo '<thead><tr>';
$colnames = $data;
} else {
echo '<tr>';
}
then you can use it in the remaining rows:
if ($row == 1) {
echo '<th scope="col">'.$value.'</th>';
}else{
echo '<td data-label="'.$colnames[$c].'">'.$value.'</td>';
}
I created a code that converts characters to binary and make table cells black/white corresponding to the ones and zeros. This is my code:
$str_splt = str_split($text);
echo "<table>";
for ($a=0;$a < count($str_splt);$a++) {
$bits = array(128,64,32,16,8,4,2,1);
$store = array(0,0,0,0,0,0,0,0);
$inp = ord($str_splt[$a]);
for ($x=0;$x < count($bits);$x++) {
if ($bits[$x] <= $inp) {
$inp = $inp - $bits[$x];
$store[$x] = 1;
} else {
$store[$x] = 0;
}
};
$store_rvs = array_reverse($store);
echo "<tr>";
for ($b=0;$b < count($store_rvs);$b++) {
if ($store_rvs[$b] == '1') {
echo "<td id=\"blk\"></td>";
}
else {
echo "<td></td>";
}
}
echo "</tr>";
}
echo "</table>";
Its output looks like this ($text = "ABCDEFGH"):
As you can see it's 8x8 table. I want to add the next set of bytes to the side of that table like this:
Each 8x8 table is a group. The two images above is group 1 and group 2:
I want to display the tables like this but I can't find the solution.
I did it in this way. Ignore my css if you are fine with yours. I replaced the id tag with class because each id should be defined once only.
echo "<html><head>";
echo "<style type='text/css'>";
echo " table, td { padding:0px; margin:0px; }";
echo " td.cell { width:15px; height:15px; }";
echo " td.blk { background-color:black; }";
echo " td.wht { background-color:yellow; }";
echo "</style>";
echo "</head><body>";
$text = "ABCDEFGH";
$text.= "ABCDEFGH";
echo "<table><tr><td><table>";
for($a=0; $a<strlen($text); $a++) {
$chr = substr($text,$a,1);
$bits = array(128,64,32,16,8,4,2,1);
$store = array(0,0,0,0,0,0,0,0);
$inp = ord($chr);
for($x=0; $x<count($bits); $x++) {
if($bits[$x] <= $inp) {
$inp = $inp - $bits[$x];
$store[$x] = 1;
} else {
$store[$x] = 0;
}
}
$store_rvs = array_reverse($store);
if($a % 8 === 0) {
echo "</table></td><td><table>";
}
echo "<tr>";
for($b=0; $b<count($store_rvs); $b++) {
if($store_rvs[$b] == '1') {
echo "<td class='cell blk'></td>";
} else {
echo "<td class='cell wht'></td>";
}
}
echo "</tr>";
}
echo "</table></td></tr></table>";
I need to get those who has more than 15 points in particular time and show in HTML page (table), the data is loaded from a CSV. The CSV file looks like below:
test.csv file
Name,Sun 0:00,Sun 1:00,Sun 2:00,Sun 3:00,Sun 4:00
John,2,0,0,0,16
Alex,0,0,0,0,0
Dan,0,15,0,0,0
Jeff,0,0,30,0,0
Peter,12,0,0,0,0
Joe,0,0,0,0,340
Bill,0,0,340,0,0`
Here is the PHP file which process the CSV and shows in HTML table.
<html>
<body>
<?php
echo "<html><body><table>\n\n";
echo "<style>\ntable,th,td\n{\nborder:1px solid black;\nborder-collapse:collapse\n}\n</style> ";
$f = fopen("test.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
if ($cell >=15)
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
?>
</body>
</html>`
But this code only provides the output as like below without the column, row label. The second table is what I'm expecting in the output.
PS: If this is can be done in jQuery/Javascript, those ideas also welcome.
Ignoring the wrong markup (you duplicate some tags), your error is that you print a cell only if the value is greater than 15. You must print always the cell instead, and print content only if it is gt 15. Example:
<html>
<body>
<style>
table,th,td
{
border: 1px solid black;
border-collapse:collapse;
}
</style>
<table>
<?php
$f = fopen("test.csv", "r");
$i = 0;
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
$j = 0;
foreach ($line as $cell) {
echo "<td>";
if ($i==0 || $j==0 || $cell >= 15) {
echo htmlspecialchars($cell);
}
echo "</td>";
$j++;
}
echo "</tr>";
$i++;
}
fclose($f);
?>
</table>
</body>
</html>
if ($cell >=15) will fail for anything that is not an integer. Hence, all string values are ignored
Instead of that use
if (trim($cell) != '')