I want to make a html table using text file data. Since I am new to web designing I dont know which approach would be best. It would be great if anyone would give me pointers on what to do.
So first off you will have to start with loading the txt file. Since you wrote in the comments about php, i guess you are using PHP as backend language.
So create a file called table.php.
In this file you can load the text file from your server / whatever and also create the html code and echo it. This will return the table line by line.
Another good solution would be to create an object out of your text file and then use JSON as transfer state for this object to your JavaScript frontend -> this is my prefered solution.
It should look similar to this (file load taken from this):
<?php
$html = '<table>'; //html variable will contain our table code
$fh = fopen('filename.txt','r'); //filename / path here
while ($line = fgets($fh)) {
$html .= '<tr>';
$html .= '<td>' + $line + '</td>';
$html .= '</tr>';
}
fclose($fh);
$html .= '</table>';
echo $html;
?>
Related
I have a Perl Script which makes a DB connection and displays the output in HTML format. The data which it's trying to display has tags embedded (<>) in it, hence the HTML does not get displayed. If I open the actual HTML file which the script generates using Notepad, I see the data. However I am unable to display it due to the tags. Any idea how this can be fixed?
#!/usr/bin/perl
use DBI;
use HTML::Escape 'escape_html';
unlink("D:\\Perl32\\scripts\\UndeliveredRAW.html");
my $host = '${Node.Caption}';
my $user = '${USER}';
my $pwd = '${PASSWORD}';
my $driver = "SQL Server";
$dbhslam = DBI->connect("dbi:ODBC:Driver=$driver;Server=$host;UID=$user;PWD=$pwd") || die "connect failed:";
$sthslam = $dbhslam->prepare("SELECT
DBA_Reports.dbo.undelivered_raw_host_msgs.ID
DBA_Reports.dbo.undelivered_raw_host_msgs.MESSAGE
FROM
DBA_Reports.dbo.undelivered_raw_host_msgs");
$sthslam->execute;
$msg = "Up";
$Count = 0;
$Output = "";
$Temp = "";
$tbl = "<TABLE border=1 bordercolor=orange cellspacing=0 cellpadding=1>";
$tblhd = "<TR><TH>ID</TH><TH>MESSAGE</TH></TR>";
while (my $ref = $sthslam->fetchrow_hashref()) {
$Count++;
$Output .= '<TR><TD align=center rowspan=1 valign=top width=1000 height=1000>'
. $ref->{'ID'}.'</TD>'
. '<TD align=center rowspan=1 valign=top width=1000 height=1000>'
. escape_html($ref->{'MESSAGE'}).'</TD></TR>';
}
$dbhslam->disconnect;
$Output = "$tbl$tblhd$Output</TABLE>";
my $filename1 = 'D:\\Perl32\\Scripts\\UndeliveredRAW.html';
open(my $fh1, '>', $filename1) or die "Could not open file '$filename1' $!";
print $fh1 "$Output";
close $fh1;
if ($Count > 0) {
$msg = $Output;
}
print "\nMessage: $msg";
print "\nStatistic: $Count";
Desired Output
Contents of HTML generated
Following code snippet demonstrates slightly modified version of posted code.
Please see the loop section for escape_html(...) usage on database obtained data.
#!/usr/bin/env perl
#
# vim: ai ts=4 sw=4
use strict;
use warnings;
use feature 'say';
use DBI;
use HTML::Escape qw/escape_html/;
my $filename = 'D:\Perl32\scripts\UndeliveredRAW.html';
unlink($filename) if -e $filename;
my $host = ${Node.Caption};
my $user = ${USER};
my $pwd = ${PASSWORD};
my $driver = 'SQL Server';
my $dbh = DBI->connect("dbi:ODBC:Driver=$driver;Server=$host;UID=$user;PWD=$pwd")
or die 'DB connect failed:';
my $query = '
SELECT
DBA_Reports.dbo.undelivered_raw_host_msgs.MESSAGE
FROM
DBA_Reports.dbo.undelivered_raw_host_msgs
';
my $rv = $dbh->do($query) or die $dbh->errstr;
my $msg = 'Up';
my $Count = 0;
my $tbl = '
<TABLE border=1 bordercolor=orange cellspacing=0 cellpadding=1>
<TR><TH>MESSAGE</TH></TR>
';
while (my $ref = $sth->fetchrow_hashref()) {
$Count++;
$tbl .= "\n\t<TR><TD align=center rowspan=1 valign=top width=5000 height=5000>"
. escape_html($ref->{'MESSAGE'})
. '</TD></TR>';
}
$tbl .= '
</TABLE>
';
my $html =
'<!DOCTYPE html>
<html>
<head>
<title>Undelivered RAW</title>
</head>
<body>
<h1>DB table data</h1>
' . $tbl . '
</body>
</html>
';
open my $fh, '>', $filename
or die "Could not open file '$filename1' $!";
print $fh $html;
close $fh;
if ($Count > 0) {
say 'Message: ' . $msg;
say 'Statistic: ' . $Count";
}
Note: to avoid polluting code with HTML style attributes find some time to learn CSS, your generated HTML does not include required sections DOCTYPE, html, head, title, body
Reference:
DBI
HTML::Escape
DBI/DBD::ODBC Tutorial
CSS
HTML
HTML has a well-understood mechanism to include characters that would normally be interpreted as special characters. For example, if you want to include a < in your HTML, that would normally be seen as starting a new HTML element in your document.
The solution is to replace those problematic characters with HTML entities that represent those characters. For example, < should be replaced with <. Note that this means the ampersand (&) needs to be added to the set of characters that should be replaced (in this case by &) if you want to include it in your HTML.
Perl has a long history of being used on the web, so it's no surprise that there are many tools available to carry out this replacement. HTML::Escape is probably the best known. It supplies a single function (escape_html()) which takes a text string and returns that same string with all of the problematic characters replaced by the appropriate entities.
use HTML::Escape 'escape_html';
my $html = '<some text> & <some other text>'
my $escaped_html = escape_html($html);
After running this code, $escaped_html now contains "$lt;some text$gt; $amp; $lt;some other text$gt;". And if you send that text to a browser, you will get the correct output displayed.
So the easiest solution is to load HTML::Escape at the top of your program and then call escape_html() whenever you're adding potentially problematic strings to your output. That means your while loop would look something like this:
while (my $ref = $sthslam->fetchrow_hashref()) {
$Count++;
$Output .= '<TR><TD align=center rowspan=1 valign=top width=5000 height=5000>'
. escape_html($ref->{'MESSAGE'})
. '</TD></TR>';
}
Note that I've removed the $Temp variable (which didn't seem to be doing anything useful) and switched to using .= to build up your output string. =. is the "assignment concatenation" operator - it adds the new string on its right to the end of whatever currently exists in the variable on its left.
You seem to be learning Perl on the job (which is great) but it's a real shame that you're learning it in an environment that seems to use techniques that have been outdated for about twenty years. Your question is a good example of why trying to build up raw HTML strings inside your Perl code is a bad idea. It's a far better idea to use a templating engine of some kind (the defacto standard in the Perl world seems to be the Template Toolkit).
I also recommend looking at Cascading Style Sheets as a more modern approach to styling your HTML output.
The below code able to read the content of file and print the content of body with the file's content.
use strict;
my $filename = '.../text.txt';
open (my $ifh, '<', $filename)
or die "Could not open file '$filename' $!";
local $/ = undef;
my #row = (<$ifh>)[0..9];
close ($ifh);
print "#row\n";
my ($body) = #_;
my ($html_body)= #_;
.
.
.
print(MAIL "Subject: Important Announcement \n");
.
.
.
push(#$html_body, "<h1><b><font color= red ><u>ATTENTION!</u></b></h1></font><br>");
push(#$html_body, "#row");
.
.
.
print(MAIL "$body", "#$html_body");
close(MAIL);
But unfortunately, i am having problem to produce the email body with same format of the text.txt file. The output email produced only having single line instead of paragraphs of 3.
The problem you're facing is that plain text contains no formatting information when placed inside a HTML document. End of line characters are ignored and treated just like ordinary white space. You need to add HTML tags to the text to convey the formatting you want or you could wrap it up in a pre tag as that will display it "as is".
As mentioned by others in the comments above, your use of #_ doesn't make sense. And it doesn't really make sense for $html_body to be treated like an array either when all you're doing is appending HTML to it. So I've rewritten that chunk of code to use it as a scalar and append the HTML to it instead. And also fixed some mistakes in the HTML as you need to close tags in the same order as you open them.
print MAIL "Subject: Important Announcement \n";
print MAIL "\n"; # Need a blank line after the header to show it's finished
my $html_body = "<html><body>";
$html_body .= "<h1><b><font color="red"><u>ATTENTION!</u></font></b></h1>";
$html_body .= "<pre>";
$html_body .= join("", #row);
$html_body .= "</pre>";
$html_body .= "</body></html>";
print MAIL $html_body;
close(MAIL);
First of all #_ is an arrayof arguments passed to subroutines, and it looks like you're not in one. So, doing:
my ($body) = #_;
my ($html_body) = #_;
is setting $body & $html_body to $_[0], which is undef.
How to fix?
There are two ways if you wrap it in a subroutine:
Use shift -> Which will make the above code look like:
my ($body) = shift;
my ($html_body)= shift;
Or,
my ($body, $html_body) = #_;
I would recommend the last one because it is less code and is more readable than the first one.
I have a table in MySQL database. It consists of many columns. The last column is BLOB column and it is storing pdf files. I want to call particular columns of the table. The BLOB column is the last one. I want the <td> elements to say Download and on click of the anchor tag I want the pdf to get downloaded. Somebody please help. The values of the Copy Column is going to be pdf files.
$result= mysql_query("SELECT Name, Type, No, Copy from table1 Join table2 where username='{$_SESSION['username']}' AND table1.UserID=table2.UserID") or die(mysql_error());
$fields_num = mysql_num_fields($result);
echo "<table class='table table-hover'>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Number</th>";
echo "<th>Copy</th>";
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>".$row['Name']."</td><td>".$row['Type']."</td><td>".$row['No']."</td><td>"."<a href=''>Download</td></tr>";
}
}
echo "</table>";
Usually I save my files in a folder and just adding the path into a column in my database and to download I use the following PHP code.
I call it downloadPop_Up.php:
<?php
$data = $_REQUEST['data'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
//header("Content-disposition: attachment; filename=\"" . basename($data) . "\"");
header("Content-disposition: attachment; filename=\"" . basename($data) . "\"");
readfile($data);
?>
I wan to always display the different pic. So there's a problem with looping the different pic. How do i do that?
index.php:
<?php
$result = mysql_query("SELECT * FROM table2", $connection );
echo '<ul>';
while($row = mysql_fetch_array($result)) {
if ($row)
echo "<li>";
echo "<img src='code.php?id=3'>";
echo " ";
echo "</p>";
echo "</li>";
echo "<br/>" ;
}
echo '</ul>';
mysql_close($connection);
?>
You need to pull the id value from the database. If you have a column called, maybe id you would want to put:
while($row = mysql_fetch_array($result)){
if ($row){
echo "<li>";
echo "<img src='code.php?id=".$row['id']."'/>"; // see what I did there?
echo " ";
echo "</p>"; // take this out
echo "</li>";
echo "<br/>"; // take this out
}
}
P.S. - don't write new code using the deprecated mysql extension. Use PDO or mysqli at least. And don't put <br />s between your <li>s, or close unopened <p>s. And, generally speaking, don't store your images in your database - just store the path to the image and put the images themselves in a folder on the server where they belong.
And please format your code - it is hard to read with no indentation or separation of files (your if statement was not properly enclosing what should have been conditioned statements). And mysql_real_escape_string is not as cool as you think it is.
Hope this helps.
I want to create a HTML page that will have a table that will populate itself with info from 2 .txt files that are on a remote Linux Server.
or populate a html page on that remote server with the same info from those 2 .txt files and then access that html page using apache's webserver.
something as basic as possible would be nice but I can understand if it's complicated to do with html
honestly, any help at all would be nice.
I would personally do it in PHP. You can read the file and echo it into a table. You can then use the lines of the file for anything you want. I put comments in explaining each step. All you have to do is change $filepath to point at your text file:
Edited: Edited the code to add constraints mentioned by OG poster in comments. There is probably a more optimized way of performing your task, but this works and should introduce some new concepts to you if you are new to PHP
<?php
$filepath = 'files/the_file.txt';
if (file_exists($filepath)) {
$file = fopen($filepath, 'r');
echo '<table border=1>';
while (!feof($file)) {
$line = fgets($file);
$first_char = $line[0];
if ($first_char != '*' && $first_char != '^' && trim($line) != '') {
if (strstr($line, '|')) {
$split = explode('|', $line);
echo '<tr>';
foreach($split as $line) {
echo '<td>'.$line.'</td>';
}
echo '</tr>';
} else {
echo '<tr><td>'.$line.'</td></tr>';
}
}
}
echo '</table>';
} else {
echo 'the file does not exist';
}
?>
I'll do my best to explain it line by line instead of flooding the scrip with comments:
set your file path
If the file exists, continue on. If not, throw the error located at the bottom of the script
open the file
create the table ('<table>')
while the text file is being read, do a series of things: First, get the line. If the first character of the line is a * or ^, or when the line is trimmed there are no characters, skip it completely. Otherwise, continue on
if the line contains a | character, split (explode) the line at all of the | characters. Use this array of split up content and for each piece of content, echo out a new column in the existing row with the current content. Otherwise, there is not | found and you can just echo the line into a row normally
once you are finished up, end the table ('</table>')
Edit #2: The original solution I posted:
<?php
$filepath = '/var/www/files/the_file.txt';
if (file_exists($filepath)) {
$file = fopen($filepath, 'r');
echo '<table border=1>';
while (!feof($file)) {
$line = fgets($file);
echo '<tr><td>'.$line.'</td></tr>';
}
echo '</table>';
} else {
echo 'the file does not exist';
}
?>
HTML can't do anything, HTML is a presentation format.
PHP, Javascript, BASH could do the job in very different ways :
PHP : the server calls the 2 remote files and output the assembled html file into a webpage, then send it to the client
Javascript : the page itself calls the 2 files and add them in itself.
Bash + CURL : a BASH (or PHP, Python...) script creates a .html file containing the data of the 2 files.
One of these might help you, if you can precreate the HTML rather than doing it dynamically. These scripts take CSV as input and output an HTML table:
http://stromberg.dnsalias.org/svn/to-table/
http://stromberg.dnsalias.org/svn/to-table2/