I have a public google spreadsheet.I got the CSV data as an array from the remote URL.Then I displayed the information as an HTML list, referencing the appropriate array items.
Now I want to fire an php select query on it such that only the gossip of a particular actor is displayed.How to do it ?
(I want to use a variable $Name.wen I supply Name.I should get the gossip of that Actor.)
my excel sheet contains following columns
> 1.Sr No.
> 2.Name
> 3.Gossip
This is the code of my php page that retrieves the data as a list :
$lines = file('https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
$headers = array_shift($lines);
foreach ($lines as $line)
{
$ldata = explode(',', trim($line));
if ($ldata[0] == '') break;
echo '<li>Sr No. <strong>' . $ldata[0] . '</strong></li><li>Name <strong>' . $ldata[1] . '</strong></li><li>Gossip <strong>' . $ldata[2] . '</strong></li>';
}
Give this a shot:
<?php
// get the CSV data as an array from the remote URL
define('GOOGLE_DOC','https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
if(isset($_GET['filterColumn'])){define('FILTER_COLUMN',$_GET['filterColumn']);}
if(isset($_GET['filterValue'])){define('FILTER_VALUE',$_GET['filterValue']);}
function readCSVIntoArray($fileName)
{
$rows=array();
if (($handle = fopen($fileName, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE){$rows[]=$data;}
fclose($handle);
}
$h=array_shift($rows);
return array($h,$rows);
}
list($head,$rows)=readCSVIntoArray(GOOGLE_DOC);
header('Content-Type: text/html; charset=utf-8');
?><!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Ultimater's Example</title>
<style type="text/css">
html,body
{
margin:0;
padding:0;
font-family:'Source Sans Pro',sans-serif;
font-size: 13px;
color:black;
background:#e2e2ec;
line-height:15px;
}
table{border-collapse:collapse;}
table thead tr th{font-weight:bold;padding:2px;margin:1px;border:1px solid black;background-color:blue;color:white;}
table tbody tr td{margin:1px;padding:2px;border:1px solid black;}
</style>
</head>
<body>
<div>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
<select name="filterColumn">
<?php foreach($head as $i=>$h){echo sprintf('<option value="%s">%s</option>',$i,htmlentities($h));} ?>
</select>
<input type="text" name="filterValue" place-holder="filter" value="" />
<input type="submit" value="Filter" />
</form>
</div>
<hr />
<?php
echo '<table>';
echo '<thead><tr><th>'.implode('</th><th>',$head).'</th></tr></thead>';
echo '<tbody>';
foreach($rows as $row)
{
if(defined('FILTER_COLUMN')&&defined('FILTER_VALUE'))
{
if(strpos($row[FILTER_COLUMN],FILTER_VALUE)===false)continue;
}
echo '<tr><td>'.implode('</td><td>',$row).'</td></tr>';
}
echo '</tbody>';
echo '</table>';
?>
</body>
</html>
Simply do not display a line if name is not like required:
<?php
// get the CSV data as an array from the remote URL
$lines = file('https://docs.google.com/spreadsheet/pub?key=0AgzUC4MxdChJdFIyMHFUZ21PS053b3Z1OHFnbHJwYVE&single=true&gid=0&output=csv');
// get rid of header row
$headers = array_shift($lines);
// Loop through data- therer is only one line hear
foreach ($lines as $line) {
$ldata = explode(',', trim($line)); // split row to its own array of elements
if ($ldata[0] == '') break; // an empty line means we are done, so exit the foreach loop
if($ldata[1] == $var_with_required_name) {
// now we can just output the information as an HTML list, referencing the appropriate array items
echo '<li>Sr No. <strong>' . $ldata[0] . '</strong></li><li>Name <strong>' . $ldata[1] . '</strong></li><li>Gossip <strong>' . $ldata[2] . '</strong></li>';
}
}
?>
Related
I want to change the color of the line 101 to 400(the last line) but i don't know how, here's my code:
echo "<html><body><table>\n\n";
$f = fopen("Productos.csv", "r");
while (($line = fgetcsv($f,1000,";")) !== false) {
echo "<tr>";
foreach ($line as $k => $cell) {
$color = ($k == 4) ? 'red' : 'white';
$class = "style='background-color: $color'";
echo "<td $class>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";
There are different approaches for such stuff, there is no right or wrong, everything depends on the specific situation. However there are some general agreements, for example that styling rules should be implemented separate from the markup.
I give two examples below. From your question I understand that you want to change the color from a certain table row on wards. However in your code you appear to work on actual table cells. I decided to change the row color from white to green for the demonstration purpose from a row index of 10 on. To prove that it is easy to also consider columns in such approach I additionally colored the third column yellow in those green rows. Obviously that is just a crude example.
Option 1: the most elegant approach in my eyes is to move the styling rules consequently into a style sheet file and not to rely on any specific markup details at all:
PHP:
<?php $fileHandle = fopen('productos.csv', 'r'); ?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="productos.css">
</head>
<body>
<table>
<tbody>
<?php while (($columns = fgetcsv($fileHandle, 1000, ';')) !== false) { ?>
<tr>
<?php foreach ($columns as $colId => $colVal) { ?>
<td><?=htmlspecialchars($colVal)?></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
CSS:
tr td {
background-color: white;
}
tr:nth-child(n+10) td {
background-color: green;
}
tr:nth-child(n+10) td:nth-child(3) {
background-color: yellow;
}
Advantages: very clean and compact markup, all styling logic and rules in one single place. Take a look at this fiddle I created for easy understanding...
Option 2: the more common approach is to enrich the markup with class names, but to keep the actual styling rules separate inside a style sheet file:
PHP:
<?php $fileHandle = fopen('productos.csv', 'r'); ?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="productos.css">
</head>
<body>
<table>
<tbody>
<?php while (($columns = fgetcsv($fileHandle, 1000, ';')) !== false) { ?>
<tr class="<?= (++$rowId>9)? 'high' : 'low' ?>">
<?php foreach ($columns as $colId => $colVal) { ?>
<td class="<?= (++$colId===3)? 'yellow' : 'green' ?>"><?=htmlspecialchars($colVal)?></td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
CSS:
tr td {
background-color: white;
}
tr.high td {
background-color: green;
}
tr.high td.yellow {
background-color: yellow;
}
Advantages: easy to read and to understand. Here is the demonstrating fiddle...
<!DOCTYPE html>
<html lang="en">
<head>
<h1>Table Generator</h1>
</head>
<body>
<center>Refresh</center>
<?php
$rows = (isset($_POST['rows']) ? $_POST['rows'] : null);
$cols = (isset($_POST['cols']) ? $_POST['cols'] : null);
$highlight = (isset($_POST['highlight']) ? $_POST['highlight'] : null);
if ($rows == "")
{
$rows = 10;
}
if ($cols == "")
{
$cols = 10;
}
if ($highlight == "")
{
$highlight = 5;
}
?>
<form method="post">
ROWS <input type="text" name="rows" value = "<?php echo $rows;?>" />
COLUMNS <input type="text" name="cols" value = "<?php echo $cols;?>" />
HIGHLIGHT <input type = "text" name = "highlight" value = "<?php echo $highlight;?>" /><br>
<input type="submit" value="Generate">
</form>
<?php
if(isset($_POST['rows']))
{
$randnumber = rand(0,100);
$rows = $_POST['rows'];
$cols = $_POST['cols'];
$highlight = $_POST['highlight'];
echo '<table border="1" align = "center">';
if (is_numeric($rows) and is_numeric($cols) and is_numeric($highlight))
{
if ($randnumber % 2 == 0)
{
echo '<center>The first number is <div class = "red">even</div></center>';
}
else
{
echo '<center>The first number is <div class = "green">odd</div></center>';
}
for($row = 1; $row <= $rows; $row++)
{
echo '<tr style = "background-color:green">';
for($col = 1; $col <= $cols; $col++)
{
if ($randnumber % $highlight == 0)
{
echo '<td style = "background-color: red">';
echo $randnumber;
$randnumber++;
echo '</td>';
}
else
{
echo '<td>';
echo $randnumber;
$randnumber++;
echo '</td>';
}
}
echo '</tr>';
}
echo '</table>';
}
else
{
echo "<center>Rows / Columns / Highlight must ALL be INTEGER values. Re-enter correct value(s).</center>";
}
echo '<pre><center>';
print_r($_POST);
echo '</center></pre>';
}
?>
<style type ="text/css">
h1 {
color: grey;
text-align:center;
}
form {
text-align: center;
padding-bottom: 20px;
}
a:link {
text-decoration: none;
}
.red {
color: red;
}
.green {
color: green;
}
</style>
</body>
</html>
So. I have this PHP code to generate a table based off the user's input and I recently ran into a problem I cant figure out how to fix.
It was working perfectly fine but now whenever I use the Refresh link it resets the entire page to default (i.e. default textbox values instead of keeping the current ones, removing the table).
So, I have 2 questions. How would I keep the data on refresh (with $_POST being used) and how to display the table with the default values when the page first loads.
Refresh
Clicking it will trigger browser's reload mechanism and you'll be asked to resubmit the form action, it will allow you to keep POST data.
You need to re-create the post if you want to keep the parameters. Can be done pretty eaily by looping thru the array.
<form method='POST' id='refresh' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<?php foreach($_POST as $k=>$v): ?>
<input type='hidden' name='<?php echo $k; ?>' value='<?php echo $v; ?>' />
<?php endforeach; ?>
<a href='#' onclick='document.getElementById("refresh").submit(); return false;'>refresh</a>
</form>
Note: This is a little longer than the other answer, but will not prompt to resend post data.
Good Day Everyone
Ok, so I have done as much as I understand and need some direction and help. Currently i'm very new to html/php so please bear with me. The plan is to list the text files from a Dir in a dropdown list, this I have done, now I would like to display the text file in the same page in a table upon submit button press. This is what I have so far, any input welcome as I am still learning!
The bash script is just a grep function to grab specific lines from the original file and copy it to /tmp.
Thanks Again
<html>
<head>
<title>Data Request</title>
</head>
<body>
<h1 align="center">Dispatch Report</h1>
<h2 align="center">Wrong Arrives Report</h2>
<table align="center" border="2">
<tr>
<td>Select Shift<br>
<form name="shiftfrm" id="shiftfrm">
<select name="shiftlist" id="shiftlist">
<option value="" selected="selected">--------</option>
<?php
$dir = opendir ("/var/www/files/");
while (false !== ($file = readdir($dir))) {
if (strpos($file, '.txt',1)) {
echo '<option value="' . $file . '">' . $file . '</option>';
}
}
?>
</select>
<input type="submit" id="submit" value="Submit"/>
<?php
if( ($handle = fopen( '/tmp/sh130418n.txt', 'r' )) !== false )
{
$output = '<table align="center" width="" border="2">';
while( ($data = fgetcsv( $handle )) !== false )
{
$output .= '<tr>';
foreach( $data as $value )
{
$output .= sprintf( '<td>%s</td>', $value );
}
fclose( $handle );
$output .= '</table>';
}
echo $output;
?>
</td></tr>
</table>
<?php
$output = exec('/var/www/cgi-bin/manualexceptget.sh');
echo "<pre>$output</pre>";
?>
</body>
</html>
assume <form method="post" action="">. Augment your file reading code:
if(!empty($_POST['shiftlist'])) {
$file = 'files/'.$_POST['shiftlist'];
if(file_exists($file)) {
if( ($handle = fopen( $file, 'r' )) !== false )
{
$output = '<table align="center" width="" border="2">';
while( ($data = fgetcsv( $handle )) !== false )
{
$output .= '<tr>';
foreach( $data as $value )
{
$output .= '<td>'.$value.'</td>';
}
$output .= '</table>';
}
echo $output;
fclose( $handle );
}
}
}
Edit: Fixed the isset() issue stated below. Changed some code, $handle was closed before reading was finished.
Edit2: I just put this in editor and saw many html tags, that were not placed properly (e.g. form not closed). Working sample at pastebin (tested on xampp)
Try Like this for (.txt) files..
<html>
<head>
<title>Data Request</title>
</head>
<body>
<h1 align="center">Dispatch Report</h1>
<h2 align="center">Wrong Arrives Report</h2>
<table align="center" border="2">
<tr>
<td>Select Shift<br />
<form name="shiftfrm" id="shiftfrm" method="POST">
<select name="shiftlist" id="shiftlist">
<option value="" selected="selected">--------</option>
<?php
$dir = opendir("files/");
while (false !== ($file = readdir($dir)))
{
if (strpos($file, '.txt', 1))
{
echo '<option value="' . $file . '">' . $file . '</option>';
}
}
?>
</select>
<input type="submit" name="submit" id="submit" value="Submit"/>
<br />
<?php
if (isset($_POST['submit']) && isset($_POST['shiftlist']))
{
if ($handle = file_get_contents('files/' . $_POST['shiftlist']))
{
$output = '<table align="center" width="" border="2">';
$output .= '<tr><td>';
echo $handle;
$output .= '</tr></td>';
$output .= '</table>';
} else
{
echo "No Content";
}
} else
{
echo "Please select the file";
}
?>
</td>
</tr>
</table>
</body>
</html>
Had this all working with html. Then I tried making it into html5 and I'm coding some of my first css code. The only thing I'm tackling right now is why isn't my image showing?? I'm using google chrome btw. The code passed in the url is this: "?fname=raichu&yesorno=true%2F" And there is no image tag in my generated html :/ I'm assuming that the if statement is equating to false??
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
td{
text-align: center;
padding:15px;
background-color:black;
color:#00FF00;}
th{
background-color:black;
color:yellow}
</style>
<title>Search Results</title>
</head>
<body style="color:#FFFFFF">
<?php
$dbhost = 'server';
$dbname = 'database1';
$dbuser = 'me';
$dbpass = 'password';
$link = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
mysqli_select_db($link,$dbname);
$naame = $_GET["fname"];
if( $_GET["yesorno"] == 'true' OR !$_GET["yesorno"])
{$query = sprintf("SELECT image_url, Type
FROM Pokemon c
WHERE c.name='%s'", mysqli_real_escape_string($link,$naame));
$result = mysqli_fetch_assoc(mysqli_query($link,$query));
echo '<img height="450" width="330" src="'.$result['image_url'].'" alt="blue"/>';}
$res = mysqli_query($link,"SELECT Name,HP,Type,Pokedex_Number AS 'Pokedex Number',Weakness,Resistance,Retreat AS 'Retreat Cost'
FROM Pokemon
WHERE Pokedex_Number!=0 AND name='$naame'");
if (!$res) {
die("Query to show fields from table failed");}
$fields_num = mysqli_num_fields($res);
echo "<h1>Stats</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{$field = mysqli_fetch_field($res);
echo "<th>{$field->name}</th>";}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($res))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
echo "</table>";
mysqli_close($link);
?>
<br />
<form method="link"
action = "http://engr.oregonstate.edu/~bainro/welcome.php" ><input
type="submit" value="(>O.O)>RETURN<(O.O<)"></form>
<p></p>
</body>
</html>
You have
&yesorno=true%2F
therefore $_GET['yesorno'] will equate to 'true/' as %2f is a forward slash.
This doesn't match
if( $_GET["yesorno"] == 'true' OR !$_GET["yesorno"])
So you're correct - that line is failed so you won't get the image.
Solution: remove the %2F from the query.
The variable you are retrieving from the url, is never evaluating to true because '%2F' is a forward slash. Check your code.
I've put together the following script which allows users to view their uploaded images in the original folder structure that they were saved.
UPDATED CODE
<?php session_start();
$_SESSION['username']=$_POST['username'];
$_SESSION['locationid']=$_POST['locationid'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<?php
//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
$galleryPath = 'UploadedFiles/' . $_SESSION['username'] . '/' . $_SESSION['locationid'] . '/';
//let's DEBUG the above assignment
if (!is_dir($galleryPath)) { die("No folder exists at $galleryPath!"); }
$absGalleryPath = realpath($galleryPath);
//let's DEBUG this one too
if (!is_dir($absGalleryPath)) { die("No folder exists at $absGalleryPath!"); }
$descriptions = new DOMDocument('1.0');
// DEBUG: let's check for the XML while we're at it
//if (!file_exists($absGalleryPath.'files.xml')) { die("No XML found at $absGalleryPath"."files.xml"); }
$descriptions->load($absGalleryPath . '/' . 'files.xml');
$items = array();
for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) {
$xmlFile = $descriptions->documentElement->childNodes->item($i);
$path = $xmlFile->getAttribute('name');
$path = explode('/', $path);
$t = &$items;
for ($j = 0; $j < count($path); $j++) {
if (empty($t[$path[$j]])) {
$t[$path[$j]] = array();
}
$t = &$t[$path[$j]];
}
$t['/src/'] = $xmlFile->getAttribute('source');
$t['description'] = $xmlFile->getAttribute('description');
$t['size'] = $xmlFile->getAttribute('size');
}
$basePath = empty($_GET['path']) ? '' : $_GET['path'];
if ($basePath) {
$basePath = explode('/', $basePath);
for ($j = 0; $j < count($basePath); $j++) {
$items = &$items[$basePath[$j]];
}
}
$files = array();
$dirs = array();
function urlpartencode(&$item, $index) {
$item = rawurlencode($item);
}
foreach ($items as $key => $value) {
if (isset($value['/src/'])) {
$value['/src/'] = explode('/', $value['/src/']);
array_walk($value['/src/'], 'urlpartencode');
$value['/src/'] = implode('/', $value['/src/']);
$files[] = array(
'name' => $key,
'src' => $value['/src/'],
'description' => htmlentities($value['description'], ENT_COMPAT, 'UTF-8'),
'size' => htmlentities($value['size'], ENT_COMPAT, 'UTF-8')
);
} else {
$dirs[] = $key;
}
}
$basePath = empty($_GET['path']) ? '' : $_GET['path'];
$up = dirname($basePath);
if ($up == '.') {
$up = '';
}
sort($files);
sort($dirs);
?>
<head>
<title>View Image Folders</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="Styles/style.css" rel="stylesheet" type="text/css" />
<script src="Libraries/jquery/jquery-1.4.3.min.js" type="text/javascript"></script>
<style type="text/css">
<!--
.style1 {
font-size: 14px;
margin-top: 5px;
margin-right: -50px;
}
-->
</style>
<body style="font-family: Calibri; color: #505050; margin-right: 160px; margin-left: -180px;">
<div align="right" class="style1"> View All Images </div>
<form id="imagefolders" name="imagefolders" class="page" action="gallery.php" method="post" enctype="application/x-www-form-urlencoded">
<div id="container">
</div>
<div id="center">
<div class="aB">
<div class="aB-B">
<?php if ('Uploaded files' != $current['title']) :?>
<?php endif;?>
<div class="demo">
<input name="username" type="hidden" id="username" value="IRHM73" />
<input name="locationid" type="hidden" id="locationid" value="1" />
<div class="inner">
<div class="container">
<div class="gallery">
<table class="gallery-link-table" cellpadding="0" cellspacing="0">
<thead>
<tr class="head">
<th class="col-name">
Name
</th>
<th class="col-size">
Size
</th>
<th class="col-description">
Description
</th>
</tr>
</thead>
<tbody>
<tr class="directory odd">
<td class="col-name">
..
</td>
<td class="col-size">
</td>
<td class="col-description">
</td>
</tr>
<?php $i = 1; ?>
<?php foreach ($dirs as $dir) : ?>
<tr class="directory <?php $i++; echo ($i % 2 == 0 ? 'even' : 'odd'); ?>">
<td><?php echo htmlentities($dir, ENT_COMPAT, 'UTF-8'); ?></td>
<td>Folder</td>
<td></td>
</tr>
<?php endforeach; ?>
<?php foreach ($files as $file) : ?>
<tr class="<?php $i++; echo ($i % 2 == 0 ? 'even' : 'odd'); ?>">
<td><a target="_blank" href="<?php echo $galleryPath . $file['src']; ?>"><?php echo htmlentities($file['name'], ENT_COMPAT, 'UTF-8'); ?></a></td>
<td><?php echo htmlentities($file['size'], ENT_COMPAT, 'UTF-8'); ?></td>
<td><?php echo htmlentities($file['description'], ENT_COMPAT, 'UTF-8'); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
I can correctly show the folders, but when I click on the folder to drill down to the individual images I receive the following error:
Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "/homepages/2/d333603417/htdocs/development/UploadedFiles/files.xml" in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 25 Warning: Invalid argument supplied for foreach() in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 65
Line 25 is this line $descriptions->load($absGalleryPath . '/' . 'files.xml'); and line 65 is this:foreach ($items as $key => $value) {`
My initial script didn't use session variables and I didn't have any issues. However I now need to include these, so I'm sure that there is a conflict between these and the foreach command. I've done quite a bit of research to see if anyone else has had similar issues, but can't find anything.
I just wondered whether someone could look at this and let me know where I'm gong wrong.
Many thanks and regards
Error 1
Warning: DOMDocument::load() [domdocument.load]: I/O warning : failed to load external entity "/homepages/2/d333603417/htdocs/development/UploadedFiles/files.xml"
The Origin of the Problem is $descriptions->load($absGalleryPath . '/' . 'files.xml');
It is bad practice trying to load file you are not sure it exists or is readable
Something like this is better and make sure you catch exception
$file = $absGalleryPath . '/' . 'files.xml' ;
if(!is_readable($file) || !file_exists($file))
{
throw new Exception("Missing XML File");
}
Error 2
Warning: Invalid argument supplied for foreach() in /homepages/2/d333603417/htdocs/development/imagefolders.php on line 65
A. Since you are not able to load the first xml document ... trying to continue the process would result to this error
B. foreach ($items as $key => $value) { so it would run independently where it is populated or not
C. Too many Referencing would make your code more difficult to understand and debug ...
Conclusion
I think you should post the content of files.xml you would be surprised it innovative solutions and ore effective code people would come up with
I think Invalid argument supplied for foreach() is about your foreach ($items as $key => $value). So place var_dump($items); before that foreach to see full dump of items variable. Seems like it's not even an array.
your foreach loop is not getting properdata as you are willing to do..pls use var_dump to check data you are getting.
check out path for your XML.