I have a page that allow user to export particular data in .xls file.
Here is the code.
if(isset($_SESSION['name'])){
$user_name=$_SESSION['name'];$sql = "select * from asset_details inner join bank_details on asset_details.user_id=bank_details.user_id inner join merchant_details on asset_details.user_id=merchant_details.user_id inner join merchant_status on asset_details.user_id=merchant_status.user_id inner join merchant_ids on asset_details.user_id=merchant_ids.user_id inner join terminal_details on asset_details.user_id=terminal_details.user_id where asset_details.user_id='$user_name' order by merchant_details.time_date asc" ; $result = mysqli_query($db,$sql); function filterData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// file name for download
$fileName = "report" . date('Ymd') . ".xls";
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($result as $row) {
if(!$flag) {
// display column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
// filter data
array_walk($row, 'filterData');
echo implode("\t", array_values($row)) . "\n";
}
exit;}
The Problem is that while exporting the data it takes column name from database rather than from the column name on the page.
My problem looks like this at the front side:
After choosing which of my users I want to export:
I'm sending AJAX request containing their database ids to external file named exportUsers.php.
So this is how back end of my problem looks like:
When data arrive to exportUsers.php, I query the database and make array($data) like this, which I want to export into Excel file.
This is how i tried to trigger download:
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$flag = false;
foreach($data as $row1) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row1)) . "\r\n";
$flag = true;
}
array_walk($row, __NAMESPACE__ . '\cleanData');
echo implode("\t", array_values($row1)) . "\r\n";
}
$filename = "users_data" . date('Ymd') . ".xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=\"$filename\"");
But this is all I see in Network tool of my browser:
But no download was triggered. Please help
Try this
session_start();
include "connection.php";
$sql= mysql_query("select * from table") or die(print "Failed Download :".mysql_error());
$columns_total = mysql_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "FileName.xls";
header('Content-type: application/xls');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
//jzend...
exit;
?>
I need to display the complete address details in Address column, but I am displayed like this:
.
Can you please help me? How to solved the issue.
<?php $users = elgg_get_entities(array( 'type' => 'user', 'limit' => 9999)); $data = array(); foreach($users as $euser){
if($euser->banned == "no" && $euser->enabled == "yes") {
if(!$euser->ext_mod){
$user = new SsportalUser($euser);
$row = array();
$row['Address'] = $user->basic('address');
array_push($data, $row);
} } }function cleanData(&$str) {
$str = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $str);
$str = preg_replace('/\s/u', '', $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; } header("Content-Disposition: attachment;filename=active_users_list.xls");header("Content-Type: application/vnd.ms-excel"); $flag = false;foreach($data as $row) {if(!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t",array_values($row))."\r\n";
}exit;
I have this function and statements running fine in my page:
$name = "JÜRGEN RÜDIGER HERMANN";
function nameReplace($name)
{
$name = str_replace("Ñ", "N", $name);
$name = str_replace("Ü", "U", $name);
$name = str_replace("Ç", "C", $name);
$name = str_replace("Á", "A", $name);
$name = str_replace("É", "E", $name);
return $name;
}
$name = nameReplace($name);
echo "This is the name!" . $name . "<br>";
$orename = "ÑÜÇÁÉ";
$orename = nameReplace($orename);
echo "Forename test: " . $orename . "<br>";
$astname = "ÁÉÑÜÇ";
$astname = nameReplace($astname);
echo "Lastname test: " . $astname . "<br>";
Everything about works fine, the characters are changed to acceptable characters for upload into a progress DB. But later in the page I'm looping through data and taking strings from a parsed HTML file:
$familyname = nameReplace($familyname);
The above familyname nameReplace() fails. If I echo out just family name it echoes out the string. If I echo out nameReplace($familyname) it returns blank or false.
Any ideas? Do functions have a specific scope?
Thanks,
Stephen.
Below is the code for the loop as requested:
for($i=1;$i<41;$i++)
{
$textfile = 'interpol_create' . $i. '_' . $date . '.txt';
$myfile = fopen($textfile, "r") or die("Unable to open file!");
if($myfile)
{
#read through the file line by line
while (($buffer = fgets($myfile, 4096)) !== false)
{
$linenumber++;
if( (strstr($buffer, '<span')) && (strstr($buffer, 'titre')))
{
$buffer = str_replace('<br />', '|', $buffer);
#echo $buffer . '<br>';
$result = explode('|', $buffer);
#family name variable
$familyname = $result[0];
$familyname = str_replace('<span class="titre">', '', $familyname);
$familyname = trim($familyname);
$familyname = nameReplace($familyname);
#first name variable
$forename = $result[1];
$forename = nameReplace($forename);
if(strstr($forename, "RGEN"))
{
echo "Forename is ".nameReplace((string)$forename)."<br>";
$newVar = "JÜRGEN RÜDIGER";
$newVar = nameReplace($newVar) . "<br>";
echo "New variable = " . $newVar . "<br>";
}
$forename = str_replace("</span>", "", $forename);
$forename = trim($forename);
#echo ($namecounter + 1) . ' | ';
#echo 'Family name : ' . $familyname . ' | Forename is : ' . $forename . '<br>';
$update_full_file .= $forename . " " . $familyname;
$firstnames[$namecounter] = $forename;
$lastnames[$namecounter] = $familyname;
}#end of if strstr $buffer
if( (strstr($buffer, 'Age today :')) && (strstr($buffer, '<br')))
{
$buffer = str_replace('<br />', '', $buffer);
$buffer = str_replace('Age today :', '', $buffer);
$agetoday = $buffer;
$agetoday = str_replace("<br/>", "", $agetoday);
$agetoday = trim($agetoday);
#echo 'Age Today : ' . $agetoday . '<br>';
$ages[$namecounter] = $agetoday;
$update_full_file .= ",," . $agetoday;
$nextlinenumber = $linenumber + 2;
$nationalitylinenumbers[$namecounter] = $nextlinenumber;
#echo $nationcounter . " " . $nextlinenumber . '<br>';
}
if( (strstr($buffer, 'Nationality :')) )
{
#$buffer = str_replace('<br />', '', $buffer);
#$buffer = str_replace('Age today :', '', $buffer);
#echo 'Nationality : ' . $buffer . '<br>';
#echo 'Line number : ' . $linenumber . '<br>';
}
if( in_array($linenumber, $nationalitylinenumbers) )
{
#echo $nationcounter . $buffer . '<br>';
#$nationcounter++;
}
###does the current linenumber appear in the array $nationalitylinenumbers?###
if( in_array($linenumber, $nationalitylinenumbers) )
{
$nation = $buffer;
$nation = str_replace("<br/>", "", $nation);
$nation = str_replace("</div>", "", $nation);
$nation = str_replace(" ", "", $nation);
#$nation = str_replace(",", "", $nation);
$nation = str_replace('<divclass="sep">', 'No Country', $nation);
$nation = trim($nation);
if(strstr($nation, ','))
{
#echo 'Create a duplicate entry';
$nations = explode(',', $nation);
$nation = $nations[0];
$nation = trim($nation);
$duplicateNation = $nations[1];
$duplicates[$duplicate_counter] .= $forename . " " .$familyname . ",," . $agetoday . ",,,,,". trim($duplicateNation) .",,,,,\n";
$duplicate_counter++;
}
#$nation = countryMappings($nation);
###check to see if entry has 2 countries###
#echo $nationcounter . $nation . '<br>';
$nationcounter++;
$update_full_file .= ",,,,," .$nation. ",,,,,\n";
$nationalitys[$namecounter] = $nation;
#echo $buffer.'<br>';
$namecounter++;
}
}#end of while buffer = fgets
}#end of if myfile
}
I managed to fix this!
The issue was I was translating the wrong data. I parsed in the 'Ü' character and was using:
$name = str_replace("Ü", "U", $name);
I exported the data to a text file and found that the character is actually exporting as Ãœ instead of Ü. I amended my function to be as below and it now works:
$name = str_replace("Ü", "U", $name);
Thanks again to all who responded, all the tips were very helpful.
Am tryng to export data to csv file from mysql. I took the following script but the $result variable have error : mysql_num_fields tells the argument supplied is not valid
$filename = 'myfile.csv';
$result = db_query("SELECT * FROM {loreal_salons}");
drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
$count = mysql_num_fields($result);
for ($i = 0; $i < $count; $i++) {
$header[] = mysql_field_name($result, $i);
}
print implode(',', $header) . "\r\n";
while ($row = db_fetch_array($result)) {
foreach ($row as $value) {
$values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
}
print implode(',', $values) . "\r\n";
unset($values);
}
If you don't mind using a temporary file, you can do:
SELECT *
INTO OUTFILE '/tmp/myfile.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM loreal_salons
as your query, then simply do:
header('Content-type: text/csv');
header('Content-disposition: attachment; filename=myfile.csv');
readfile('/tmp/myfile.csv');
unlink('/tmp/myfile.csv');
exit();