is there any other way to extract serialized data from sql to excel? I tried to do this
<?php
$hostname_dbconnect = "localhost";
$database_dbconnect = "upload_dodwnload";
$username_dbconnect = "root";
$password_dbconnect = "";
$dbconnect = mysql_pconnect($hostname_dbconnect, $username_dbconnect, $password_dbconnect) or trigger_error(mysql_error(),E_USER_ERROR);
?>
<?php
$query = "SELECT * FROM tbl_emp_sched";
$result = mysql_query($query) or die ("no query");
$row_try=mysql_fetch_array($result);
$numrows=mysql_num_rows($result);
/*
$empid=unserialize($row_try['Employee_ID']);
$empname=unserialize($row_try['Emp_FullName']);
$empwrk=unserialize($row_try['Emp_WrkFrcCode']);
$empsch=unserialize($row_try['Emp_SchdCode']);
$datas= array(
"0" => $empid,
"1" => $empname,
"2" => $empwrk,
"3" => $empsch
);
print_r ($datas);
*/
$array_try = array($result['Employee_ID'],$result['Emp_FullName'],$result['Emp_WrkFrcCode'],$result['Emp_SchdCode']);
while($datas = mysql_fetch_array($result))
{
$array_try[] = $datas;
}
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
$filename = "Rota_Schedule_(Schedule Codes)" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($array_try as $datas) {
if(!$flag) {
echo implode("\t", array_keys($datas)) . "\n";
$flag = true;
}
array_walk($datas, 'cleanData');
echo implode("\t", array_values($datas)) . "\n";
}
?>
but i don't get what i want. Anybody can help me? This problem causing me hours and hours of testing, any other idea? I tried to unserialize it first but the code just gone crazy and not working properly. Anybody can help me? Thanks
Related
I have code which download the excel file.
I want to save this file in folder.
if($array_count > 0)
{
$fileName = "export_data" . rand(1,100) . ".xls";
if ($error_array) {
function filterData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
foreach($error_array as $row) {
if(!$flag) {
// display column names as first row
// echo implode("\t", array_keys($row)). "\r\n";;
$flag = true;
}
// filter data
//header_remove('require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php")');
array_walk($row, 'filterData');
echo implode("\t", array_values($row)). "\r\n"; ;
}
//exit;
}
}
Please some one help me to change my code to save file in folder.
Here I have made one sample for you with static array data. We can save the file in the folder.
You can make changes in this code as per your requirement.
<?php
$data_array = array (
array ('1','2'),
array ('2','2'),
array ('3','6'),
array ('4','2'),
array ('6','5')
);
$sep = "\t";
$xls = "col1".$sep."col2 \n";//Column headers
foreach ($data_array as $record){
$xls.= $record[0].$sep.$record[1]."\n"; //Append data to xls
}
$xls_handler = fopen ('xlsfile.xls','w');
fwrite ($xls_handler,$xls);
fclose ($xls_handler);
echo 'Data saved to xlsfile.xls';
?>
i am doing an ajax call and called a php page which is extracting data from a mysql table and need to convert it to excel and need to store in server folder only.
Now the problem is while doing the ajax call, its going to that php page and returning to the main page without creating the excel file.
But when i tested the php page directly then its creating the excel file and downloading it. But why its not working via ajax call.
This is my ajax call from previous page --
$.ajax({
type: "POST",
url: "admin-advertiser-details-exports.php?selectedColumns="+selectedColumns+"&excelColumn="+excelColumn,
contentType:false,
processData:false,
success:function(data){
alert('Export done');
}
});
And this is my php page which is exporting to excel --
<?php
session_start();
include 'db.php';
if(!isset($_SESSION))
{
$uname=$_SESSION['uname'];
}
else if(empty($_SESSION['uname']))
{
header('Location: index.php',TRUE);
}
$UserName = $_SESSION['uname'];
$UserID = $_SESSION['uid'];
$UserType = $_SESSION['utype'];
$selectedColumns = $_GET['selectedColumns'];
$excelColumn = $_GET['excelColumn'];
$array = explode('\t',$excelColumn);
$sql = "select ".$selectedColumns." from advertisers_details ad join user_details ud on ad.adv_manager=ud.user_id order by ad.adv_id asc";
$setRec = mysqli_query($linkID1, $sql);
$columnHeader = '';
foreach ($array as $value) {
$value = '"' . $value . '"' . "\t";
$columnHeader .= $value;
}
$setData = '';
while ($rec = mysqli_fetch_row($setRec))
{
$rowData = '';
foreach ($rec as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=advertiser_detail.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
If i am running this php page directly the i am getting the excel file, but via ajax call its not working.
Hope this example work best for you.
I have used window.open and set url of target file with parameter.
JS code used
/* Export Orders */
$(document).on('click','#btn_export_delivery_order',function(){
var first_input = $('#name_email_order_search').val();
var date_range = $('#reportrangeorder').val();
var order_status = $('#order_status').val();
window.open("ajax_responce.php?method_name=export_orders&shop="+ shop+"&first_input=" + first_input + "&date_range=" + date_range + "&order_status=" + order_status + "", '_blank');
});
Code used in ajax_response.php
public function export_orders(){
ob_start();
if (isset($_GET['shop']) && $_GET['shop'] != '') {
$export = array();
$export_data = array();
$shopinfo = $this->get_settings($_GET['shop']);
$store_client_id = $shopinfo['store_client_id'];
$date_format = $shopinfo['date_format_first'];
$options_arr = array("skip" => 0, "limit" => 99999);
$where = $this->where_to_clause_export_search($store_client_id, $_GET);
$fullfilment_status_array = array('Unfulfilled','Fullfill','Partially fullfill','Cancelled');
$export_result = $this->select_result(TABLE_ORDERS, '*', $where, $options_arr);
foreach($export_result['data'] as $row){
$export['Name'] = $row['order_name'];
$export['Billing Name'] = $row['first_name'] . ' ' . $row['last_name'];
$export['Email'] = $row['email'];
$export['Fulfillment Status'] = $fullfilment_status_array[$row['status']];
$export['Total'] = $row['total'];
$export['Created at'] = date($date_format, strtotime($row['created_at']));
$export['Delivery Status'] = $row['delivery_status'] == 0 ? 'Pending' : 'Delivered';
$export['Delivery Date'] = date($date_format, strtotime($row['delivery_date']));
$export['Delivery Time'] = (isset($row['delivery_time']) && $row['delivery_time'] != '') ? $row['delivery_time'] : '-';
$export_data[] = $export;
}
/* Export Data */
$filename = "orders_export.csv";
$f = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
$outputdata = $export_data;
$firstLineKeys = false;
foreach ($outputdata as $row) {
if (empty($firstLineKeys)) {
$firstLineKeys = array_keys($row);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
fputcsv($f, $row);
}
fclose($f);
ob_end_flush();
exit();
}
}
This code is tested well and working fine.
Im currently trying to write a few words on a file, and then open it.
currently, i do have the following outcome:
When my desired outcome would be something like:
How come it is like that?
TextAr is just some numbers from a textarea. ( one id each line)
code:
$text = preg_replace('/\n+/', "\n", trim($_POST['ids']));
$textAr = explode("\n", $text);
foreach ($textAr as $k=>$v) if(empty(trim($v))) unset($textAr[$k]);
$textAr = array_filter($textAr, 'trim');
$handle = fopen("file.txt", "w");
$saveresult = '';
foreach ($textAr as $line) {
$line = str_replace(' ', '', $line);
$line = preg_replace('/\D/', '', $line);
$result = httpPost($url, $line);
$showID = ($showID ? "".$result['id']." -" : '');
$notexisting = ($showasnull ? 0 : "N/A");
if ($result['manual'] == true) {
$saveresult .= "".$showID." Manual".PHP_EOL;
}
if ($result['hit'] == true && $result['manual'] != true) {
$saveresult .= "".$showID." " . $result['price'] . "".PHP_EOL;
} else if ($result['hit'] == false) {
$saveresult .= "".$showID." ".$notexisting."".PHP_EOL;
}
$saveresult .= "\r\n";
?>
<?PHP }
fwrite($handle, $saveresult);
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
EDIT
i removed $saveresult .= "\r\n"; but still same result.
EDIT 2:
example of textAr:
array(2) { [0]=> string(8) "43631132" [1]=> string(8) "43631132" }
example of $result
array(4) { ["id"]=> string(8) "43631132" ["price"]=> int(0) ["hit"]=> bool(false) ["manual"]=> bool(false) }
You can write each line independantly. This way you can check if the line itself is empty before writing.
foreach ($textAr as $line) {
$saveresult = "";
$line = str_replace(' ', '', $line);
$line = preg_replace('/\D/', '', $line);
$result = httpPost($url, $line);
$showID = ($showID ? "".$result['id']." -" : '');
$notexisting = ($showasnull ? 0 : "N/A");
if ($result['manual'] == true) {
$saveresult .= "".$showID." Manual";
}
if ($result['hit'] == true && $result['manual'] != true) {
$saveresult .= "".$showID." " . $result['price'];
} else if ($result['hit'] == false) {
$saveresult .= "".$showID." ".$notexisting;
}
$saveresult = trim($saveresult);
if (!empty($saveresult)) {
fwrite($handle, $saveresult.PHP_EOL);
}
}
fclose($handle);
i am trying to convert pdf file to excel.
So first i have fetched the data from pdf and adding that to excel
when i have hard-coded the values then it is working file but i want code without hard-coding my code is:-
$result = pdf2text ('1.pdf');
$array1 = explode('***', $result );
function filterData(&$str) {
$str = preg_replace("/\t/", "\t", $str); $str = preg_replace("/\r? \n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; }
$data = array(
array($array1[0]),
array($array1[1]),
array($array1[2])
);
$fileName = "codexworld_export_data" . date('Ymd') . ".xls";
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
foreach($data as $row) {
array_walk($row, 'filterData');
echo implode("\t", array_values($row)) . "\n";
}
exit;
above code is working fine but i don't want to mention array1 as $array1[0],$array1[1],$array1[2].
because my pdf file may have multiple values also so please tell me how to assign $array1 to $data
Try Like this..
$array1 =array('aaa',22);//an assumed array
foreach ($array1 as $key=>$value)
{
$data[] = array($value);
}
print_r($data);
hello i have this code to export my data from to .xls but i have problem with encoding, this is my code
<?php
header("Content-Type: text/plain;charset=UTF-8");
function cleanData(&$str)
{
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
$data = array(
array('firstname' =>'Name', 'last_name' => 'Last Name', 'age' => '25'),
array('firstname' =>'name 2', 'last_name' => 'Last Name 2', 'age' => '27')
);
$flag = false;
foreach($data as $row) {
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\r\n";
}
exit;
?>
I try the Encoding iso-8859-7, and windows-1253, and UTF-8 i want to export with greek characters all my data is in UTF-8. Thank you for help
<?php
include('connect.php');
header("Content-Type: text/plain; charset=UTF-8");
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv; charset=UTF-8");
$out = fopen("php://output", 'w');
$flag = false;
$result = mysql_query("SELECT * FROM categories ORDER BY id") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = true;
}
array_walk($row, 'cleanData');
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
?>
I change my code and in text editor i can see my characters is fine and the encoding is in greek, but when i open in microsoft excel it's unreadable