How to display only title field name in xl file using php - php

Here i want to do read the xl file in php,here i displayed all datas that means in xl file i have four columns called Title,Url,Visitors,Accesses.but for me don't want like this , i want only title name how can do this ? View my answer
<?php
include 'excel_reader.php'; // include the class
// creates an object instance of the class, and read the excel file data
$excel = new PhpExcelReader;
$excel->read('test.xls');
function sheetData($sheet) {
$re = '<table>'; // starts html table
$row = 1;
while($row <= $sheet['numRows']) {
$re .= "<tr>\n";
$column = 1;
$cell = isset($sheet['cells'][$row][1]) ? $sheet['cells'][$row][1] : '';
$re .= " <td>$cell</td>\n";
$re .= "</tr>\n";
$row++;
}
return $re .'</table>';// ends and returns the html table
}
$nr_sheets = count($excel->sheets);// gets the number of sheets
$excel_data = ''; // to store the the html tables with data of each sheet
// traverses the number of sheets and sets html table with each sheet data in $excel_data
for($i=0; $i<$nr_sheets; $i++) {
//$excel_data .= '<h4>Sheet '. ($i + 1) .' (<em>'. $excel->boundsheets[$i]['name'] .'</em>)</h4>'. sheetData($excel->sheets[$i]) .'<br/>';
$excel_data .= sheetData($excel->sheets[$i]) .'<br/>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example PHP Excel Reader</title>
<style type="text/css">
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<?php
// displays tables with excel file data
echo $excel_data;
?>
</body>
</html>

By observing the $sheet array you will get Title at the position of 4,1 as follows.
By changing this line as shown
$cell = isset($sheet['cells'][4][1]) ? $sheet['cells'][4][1] : '';
But it looks like you have copied this code from somewhere. It is hard to identify your need and modify it. Change the code as per your requirement and if any error occurs then post your question on SO
as per your requirement your sheetData function should be like this
function sheetData($sheet) {
$re = '<table>'; // starts html table
$x = 1;
while($x <= $sheet['numRows']) {
$re .= "<tr>\n";
$cell = isset($sheet['cells'][$x][1]) ? $sheet['cells'][$x][1] : '';
if($cell != 'Title'){ // check for title here
$re .= " <td>$cell</td>\n";
$re .= "</tr>\n";
}
$x++;
}
return $re .'</table>'; // ends and returns the html table
}

Related

how to read specific row from excel file to display information on html output using PHP code?

how to read specific row from excel file to display information on html output using PHP code?
<?php
include 'excel_reader.php'; // include the class
// creates an object instance of the class, and read the excel file data
$excel = new PhpExcelReader;
$excel->read('fees.xls');
// Excel file data is stored in $sheets property, an Array of worksheets
/*
The data is stored in 'cells' and the meta-data is stored in an array called 'cellsInfo'
Example (firt_sheet - index 0, second_sheet - index 1, ...):
$sheets[0] --> 'cells' --> row --> column --> Interpreted value
--> 'cellsInfo' --> row --> column --> 'type' (Can be 'date', 'number', or 'unknown')
--> 'raw' (The raw data that Excel stores for that data cell)
*/
// this function creates and returns a HTML table with excel rows and columns data
// Parameter - array with excel worksheet data
function sheetData($sheet) {
$re = '<table>'; // starts html table
$x = 1;
while($x <= $sheet['numRows']) {
$re .= "<tr>\n";
$y = 1;
while($y <= $sheet['numCols']) {
$cell = isset($sheet['cells'][$x][$y]) ? $sheet['cells'][$x][$y] : '';
$re .= " <td>$cell</td>\n";
$y++;
}
$re .= "</tr>\n";
$x++;
}
return $re .'</table>'; // ends and returns the html table
}
$nr_sheets = count($excel->sheets); // gets the number of sheets
$excel_data = ''; // to store the the html tables with data of each sheet
// traverses the number of sheets and sets html table with each sheet data in $excel_data
for($i=0; $i<$nr_sheets; $i++) {
$excel_data .= '<h4>Sheet '. ($i + 1) .' (<em>'. $excel->boundsheets[$i]['name'] .'</em>)</h4>'. sheetData($excel->sheets[$i]) .'<br/>';
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example PHP Excel Reader</title>
<style type="text/css">
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<?php
// displays tables with excel file data
echo $excel_data;enter code here
?>
</body>
</html>
This function will return any row the user give s as the input if values exist.
// this function creates and returns a HTML table with excel row given
// Parameter 1 - array with excel worksheet data
// Parameter 2 - any row you want to print
function sheetRowData($sheet,$rowNum) {
$re = '<table>'; // starts html table
$x = $rowNum; //get users Row Number as $x
if($x <= $sheet['numRows']) {
$re .= "<tr>\n";
$y = 1;
while($y <= $sheet['numCols']) {
$cell = isset($sheet['cells'][$x][$y]) ? $sheet['cells'][$x][$y] : '';
$re .= " <td>$cell</td>\n";
$y++;
}
$re .= "</tr>";
return $re .'</table>'; // ends and returns the html table row
}else{
return "row not found";
}
}
Hope it helps :)

div and class not showing up

I'm testing a barcode on my website but for some reason the div with the class="b128" which stands for the barcodes is not showing up. If I test the same source code on another website it does show up but with different styling.
Does anyone know how I can make this source code show up and keep the original styling at the same time?
<style>
div.b128{
border-left: 1px black solid;
height: 60px;
}
</style>
<?php
global $char128asc,$char128charWidth;
$char128asc=' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$char128wid = array(
'212222','222122','222221','121223','121322','131222','122213','122312','132212','221213', // 0-9
'221312','231212','112232','122132','122231','113222','123122','123221','223211','221132', // 10-19
'221231','213212','223112','312131','311222','321122','321221','312212','322112','322211', // 20-29
'212123','212321','232121','111323','131123','131321','112313','132113','132311','211313', // 30-39
'231113','231311','112133','112331','132131','113123','113321','133121','313121','211331', // 40-49
'231131','213113','213311','213131','311123','311321','331121','312113','312311','332111', // 50-59
'314111','221411','431111','111224','111422','121124','121421','141122','141221','112214', // 60-69
'112412','122114','122411','142112','142211','241211','221114','413111','241112','134111', // 70-79
'111242','121142','121241','114212','124112','124211','411212','421112','421211','212141', // 80-89
'214121','412121','111143','111341','131141','114113','114311','411113','411311','113141', // 90-99
'114131','311141','411131','211412','211214','211232','23311120' ); // 100-106
////Define Function
function bar128($text) { // Part 1, make list of widths
global $char128asc,$char128wid;
$w = $char128wid[$sum = 104]; // START symbol
$onChar=1;
for($x=0;$x<strlen($text);$x++) // GO THRU TEXT GET LETTERS
if (!( ($pos = strpos($char128asc,$text[$x])) === false )){ // SKIP NOT FOUND CHARS
$w.= $char128wid[$pos];
$sum += $onChar++ * $pos;
}
$w.= $char128wid[ $sum % 103 ].$char128wid[106]; //Check Code, then END
//Part 2, Write rows
$html="<table cellpadding=0 cellspacing=0><tr>";
for($x=0;$x<strlen($w);$x+=2) // code 128 widths: black border, then white space
$html .= "<td><div class=\"b128\" style=\"border-left-width:{$w[$x]};width:{$w[$x+1]}\"></div>";
return "$html<tr><td colspan=".strlen($w)." align=center><font family=arial size=2><b>$text</table>";
}
?>
<?php
$test = "12345";
echo '<div style="border:3px double #ababab; padding:5px;margin:5px auto;width:135px;">';
echo bar128(stripslashes($test));
echo '</div>';
?>
You aren't closing most of your tags. Try this:
$html = "<table cellpadding=0 cellspacing=0><tr>";
for ($x = 0; $x < strlen($w); $x += 2) // code 128 widths: black border, then white space
$html .= "<td><div class=\"b128\" style=\"border-left-width:{$w[$x]};width:{$w[$x+1]}\"></div></td>";
return "$html</tr><tr><td colspan=" . strlen($w) . " align=center><font family=arial size=2><b>$text</b></font></td></tr></table>";

Exporting a dynamic table to Excel in PHP

I have a large table with an unknown amount of columns that I want to be able to export to MS Excel via a download link. I have done this before with no issues. However, that was when I had a known number or columns. I currently am able to successfully send data to an Excel file. The table headers display correctly across the top of the table. The problem is with the data. Instead of placing the data across the page in the correct columns, it is putting it all in the first column. Here is part of my code:
while($row = mysql_fetch_row($result))
{
// Loops through the results
for($i=0; $i < $num_cols; $i++)
{
// Prints out the data in a table cell
echo("<Td class='data'>$row[$i]</Td>");
$FileRecord = Array($row[$i]);
$exportFile->Export_Record($FileRecord);
}
}
Normally I do $FileRecord = Array($row[0], $row[1], ..., $row[n]) and everything works great, but I am not sure how to do that if I don't know how many columns there are. Any help would be great!
I am not using any library. $exportFile is from a function that I am using. It looks like this:
class CSV_File {
private $out='';
private $name='';
private $column_names="";
private $count = 0;
//Creates the file name and the header columns
function __Construct($buf, $names) {
$GLOBALS["name"] = $buf;
$GLOBALS["column_names"] = ($names."\n");
}
public function Export_Record($array) {
if (!is_array($array))
throw new Exception("NOT AN ARRAY");
for ($i = 0; $i <= count($array); $i++) {
$GLOBALS["out"] .= $array[$i];
if ($i < count($array)-1) {
$GLOBALS["out"] .= ",";
}
}
$GLOBALS["out"] .= "\n";
$GLOBALS["out"]++;
}
public function ExportButton($align) {
$output = $GLOBALS["out"];
$filename = $GLOBALS["name"];
$columns = $GLOBALS["column_names"];
if ($align == null)
$align = "align";
echo(" <$align><form name=\"export\" action=\"export.php\" method=\"post\">
<button type=\"submit\" style='border: 0; background: transparent; font-size: 12px;font-weight:bold;'>
<img src = 'images/icon_csv.png' width = '16' height ='16' alt ='Download Data'> Download</button>
<input type=\"hidden\" value=\"$columns\" name=\"csv_hdr\">
<input type=\"hidden\" value=\"$filename\" name=\"fileprefix\">
<input type=\"hidden\" value=\"$output\" name=\"csv_output\">
</form></align>");
}
}
And then export.php looks like this:
if (isset($_POST['csv_hdr']))
{
$out .= $_POST['csv_hdr'];
$out .= "\n";
}
if (isset($_POST['csv_output']))
{
$out .= $_POST['csv_output'];
}
if (isset($_POST['fileprefix']))
{
$fname .= $_POST['fileprefix'];
}
//Now we're ready to create a file. This method generates a filename based on the current date & time.
$filename = $fname."_".date("Y-m-d_H-i",time());
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;'
That's not an Excel table. It's an html table that you just happen to be feeding into Excel.
Your problem is that you're not starting a new table row for every record you're fetching, so everything just becomes a new cell in the first row.
You need something like
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
foreach($row as $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}

How to search inside GCIDE XML using PHP

I downloaded GCIDE (GNU Project's publication of CIDE, the Collaborative International Dictionary of English) from its website.
The package contains various XML files. I am running PHP with Apache in my Windows PC. How can I search for a word and its definition in these XML files using PHP?
Your project intrigued me, and thought I might find it useful sometime, so did some research, and found the below code on this page. I ran this php, and currently have a fully functional dictionary in my database!
Here's everything I did to get it up and running (I unzipped the XML files into a folder called XML within the folder that contains these files).
SQL for Table - gcide
CREATE TABLE `gcide` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`word` varchar(255) DEFAULT NULL,
`definition` text,
`pos` varchar(50) DEFAULT NULL,
`fld` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `word` (`word`)
) ENGINE=MyISAM
PHP for gcide XML Import - import_gcide_xml.php
<?php
$connection = mysql_connect('localhost', 'root', '') or die('Could not connect to MySQL database. ' . mysql_error());
$db = mysql_select_db('fiddle',$connection);
mysql_query('TRUNCATE TABLE gcide') or die(mysql_error());
$xml = array('xml/gcide_a.xml', 'xml/gcide_b.xml', 'xml/gcide_c.xml', 'xml/gcide_d.xml', 'xml/gcide_e.xml','xml/gcide_f.xml','xml/gcide_g.xml', 'xml/gcide_h.xml', 'xml/gcide_i.xml', 'xml/gcide_j.xml', 'xml/gcide_k.xml', 'xml/gcide_l.xml', 'xml/gcide_m.xml', 'xml/gcide_n.xml', 'xml/gcide_o.xml', 'xml/gcide_p.xml', 'xml/gcide_q.xml', 'xml/gcide_r.xml', 'xml/gcide_s.xml', 'xml/gcide_t.xml', 'xml/gcide_u.xml', 'xml/gcide_v.xml', 'xml/gcide_w.xml', 'xml/gcide_x.xml', 'xml/gcide_y.xml', 'xml/gcide_z.xml');
$numberoffiles = count($xml);
for ($i = 0; $i <= $numberoffiles-1; $i++) {
$xmlfile = $xml[$i];
// original file contents
$original_file = #file_get_contents($xmlfile);
// if file_get_contents fails to open the link do nothing
if(!$original_file) {}
else {
// find words in original file contents
preg_match_all("/<hw>(.*?)<\/hw>(.*?)<def>(.*?)<\/def>/", $original_file, $results);
$blocks = $results[0];
// traverse blocks array
for ($j = 0; $j <= count($blocks)-1; $j++) {
preg_match_all("/<hw>(.*?)<\/hw>/", $blocks[$j], $wordarray);
$words = $wordarray[0];
$word = addslashes(strip_tags($words[0]));
$word = preg_replace('{-}', ' ', $word);
$word = preg_replace("/[^a-zA-Z0-9\s]/", "", $word);
preg_match_all("/<def>(.*?)<\/def>/", $blocks[$j], $definitionarray);
$definitions = $definitionarray[0];
$definition = addslashes(strip_tags($definitions[0]));
$definition = preg_replace('{-}', ' ', $definition);
$definition = preg_replace("/[^a-zA-Z0-9\s]/", "", $definition);
preg_match_all("/<pos>(.*?)<\/pos>/", $blocks[$j], $posarray);
$poss = $posarray[0];
$pos = addslashes(strip_tags($poss[0]));
$pos = preg_replace('{-}', ' ', $pos);
$pos = preg_replace("/[^a-zA-Z0-9\s]/", "", $pos);
preg_match_all("/<fld>(.*?)<\/fld>/", $blocks[$j], $fldarray);
$flds = $fldarray[0];
$fld = addslashes(strip_tags($flds[0]));
$fld = preg_replace('{-}', ' ', $fld);
$fld = preg_replace("/[^a-zA-Z0-9\s]/", "", $fld);
$insertsql = "INSERT INTO gcide (word, definition, pos, fld) VALUES ('$word', '$definition', '$pos', '$fld')";
$insertresult = mysql_query($insertsql) or die(mysql_error());
echo $word. " " . $definition ."\n";
}
}
}
echo 'Done!';
?>
CSS For Search Page - gcide.css
body{ font-family:Arial, Helvetica, sans-serif; }
#search_box { padding:4px; border:solid 1px #666666; margin-bottom:15px; width:300px; height:30px; font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; }
#search_results { display:none;}
.word { font-weight:bold; }
.found { font-weight: bold; }
dl { font-family:serif;}
dt { font-weight:bold;}
dd { font-weight:normal;}
.pos { font-weight: normal;}
.fld { margin-right:10px;}
HTML for Search Page - index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search of GCIDE</title>
<link href="gcide.css" rel="stylesheet" type="text/css"/>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$("#search_box").keyup(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "gcide_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#search_results").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="ui-widget-content" style="padding:10px;">
<input id="search_box" class='search_box' type="text" />
<div id="search_results">Search results for <span class="word"></span></div>
<dl id="results"></dl>
</div>
</body>
</html>
PHP for jQuery Search - gcide_search.php
<?php
if (isset($_POST['search'])) {
$db = new pdo("mysql:host=localhost;dbname=fiddle", "root", "");
// never trust what user wrote! We must ALWAYS sanitize user input
$word = mysql_real_escape_string($_POST['search']);
$query = "SELECT * FROM gcide WHERE word LIKE '" . $word . "%' ORDER BY word LIMIT 10";
$result = $db->query($query);
$end_result = '';
if ($result) {
while ( $r = $result->fetch(PDO::FETCH_ASSOC) ) {
$end_result .= '<dt>' . $r['word'];
if($r['pos']) $end_result .= ', <span class="pos">'.$r['pos'].'</span>';
$end_result .= '</dt>';
$end_result .= '<dd>';
if($r['fld']) $end_result .= '<span class="fld">('.$r['fld'].')</span>';
$end_result .= $r['definition'];
$end_result .= '</dd>';
}
}
if(!$end_result) {
$end_result = '<dt><div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;">
<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
No results found.</p>
</div></dt>';
}
echo $end_result;
}
?>
I happend to stumble across this PHP and AJAX example a little while back - it might get you pointed in the right direction, but with that much data, you might want to consider importing it into a database and use it's searching capabilities- that's what they're designed for, whereas performance will likely be an issue chugging through that much plain text of an XML file. Take a look at this answer for XML importing. Also found this SO answer about importing GCIDE XML.

PHP mailing database search

I made a PHP page that looks up Constant Contact e-mail addresses in a database and returns a table listing their name, e-mail address, and mailing list they are in. You enter the addresses here: Contact Lookup Tool along with your Constant Contact user name and password.
For some reason, only the last row of the results page has a list of mailing lists. The other ones have the word "Array," which I stripped out, so now those rows are blank. Here is a screen shot of what I mean:
http://www.advantage-computer.com/images/ScreenCap.png
They're all in a list, though. Here's the code for search.php. The form submits to that file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>List of Contacts</title>
<style type="text/css">
.hdr
{
margin-bottom: 0px;
padding-bottom: 0px;
}
</style>
</head>
<body>
<table width="75%">
<tr>
<td class="hdr">Name</td>
<td class="hdr">E-mail address</td>
<td class="hdr">List(s)</td>
</tr>
<tr>
<td colspan="3">
<hr style="padding:0; margin:0">
</td>
</tr>
<?PHP
require_once('./class.cc.php');
/*VARIABLES*/
$cc = new cc($_POST['userName'], $_POST['password']);
if($cc)
{
$strEmails = $_REQUEST['emails'];
$aryEmails = explode("\n", $strEmails);
$page = (isset($_GET['page'])) ? $_GET['page'] : 'lists';
$lists = $cc->get_lists($page);
/*METHODS*/
foreach ($aryEmails as $email)
{
if($lists)
{
foreach($lists as $k => $v)
{
$list = $v['Name'];
$page = (isset($_GET['page'])) ? $_GET['page'] : 'members';
$members = $cc->get_list_members($v['id'], $page);
if($members)
{
foreach($members as $k => $v)
{
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
}
}
}
}
}
$strLists = str_replace("Array", "", $strLists);
$strLists = substr($strLists, 0, -2);
$contact = $cc->query_contacts(trim($email));
if($contact)
{
$strName = $contact['Name'];
if(is_array($strName))
{
$strName = "";
}
echo
(
"<tr><td>".$strName."</td>".
"<td>".$contact['EmailAddress']."</td>".
"<td>".$strLists."</td></tr>"
);
}
else
{
echo("<tr><td colspan='3'>Could not find {$email}.</td></tr>");
}
}
}
else
{
echo "Invalid user name or password";
}
?>
</table>
</body>
</html>
Here is the class.cc file: http://advantage-computer.com/tools/class.cc.txt
Firstly, you should break out of that loop once you have matched a record, and you are not using $k so we can remove that from the loop too, eg:
if($members)
foreach($members as $v)
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
break;
}
I would also add a line in there to debug whats in the $list variable when it is an array:
if (is_array($list))
var_dump($list);
I would say that whatever is setting "$_list['content']['ContactList']['Name']" in your class is not doing it correctly.
Thanks everyone for the replies. My brother found the problem. He changed
foreach ($aryEmails as $email){
...
}
to
foreach ($aryEmails as $tmpEmail){
$email = rtrim($tmpEmail);
...
}
It appears that it only matched the last line in the text area because there were still carriage returns in the e-mail array left over from the text area. He added rtrim to remove them.

Categories