Exemple #1
1
function csvFromKeyedArray($keyedArray, $filename = NULL)
{
    $headers = array_keys($keyedArray[0]);
    $headerRow = str_putcsv($headers);
    $csvBody = array2csv($keyedArray);
    return "{$headerRow}\n{$csvBody}";
}
 function getcsv($array, $download = "")
 {
     if ($download != "")
     {    
         header('Content-Type: application/csv');
         header('Content-Disposition: attachement; filename="' . $download . '"');
         echo array2csv($array);
         exit;
     }        
     die;
      
 }
Exemple #3
0
 function download()
 {
     $data = filter_forwarded_data($this);
     $this->load->helper('report');
     $report = $this->_report->report_to_array($data['t']);
     # download CSV
     if ($data['t'] == 'download_csv') {
         send_download_headers("file_" . strtotime('now') . ".csv");
         echo array2csv($report);
         die;
     } else {
         if ($data['t'] == 'download_pdf') {
             $this->load->model('_file');
             $reportType = $this->native_session->get('__report_type') ? $this->native_session->get('__report_type') : 'procurement_plan_tracking';
             $this->_file->generate_pdf(generate_report_html($report, $reportType), UPLOAD_DIRECTORY . 'file_' . strtotime('now') . '.pdf', 'download', array('size' => 'A4', 'orientation' => 'landscape'));
         }
     }
 }
    $headers[] = 'pos_start';
    $headers[] = 'pos_end';
    $headers[] = 'description';
    $headers[] = 'coref_group';
    $headers[] = 'author';
    $headers[] = 'date_added';
    fputcsv($df, $headers);
    foreach ($array as $row) {
        fputcsv($df, $row);
    }
    fclose($df);
    return ob_get_clean();
}
function download_send_headers($filename)
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");
    // force download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
download_send_headers("coref_export_" . date("Y-m-d") . ".csv");
echo array2csv($qbc->getAllCorefs());
die;
Exemple #5
0
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
// ****************************************************************
// access check
include "includes/startloggedinadmin.inc.php";
require_once "classes/constants.class.php";
//require_once "classes/template.class.php";
//require_once "classes/templatehelper.class.php";
require_once "classes/db.class.php";
require_once "classes/sessionhelper.class.php";
//require_once "classes/jswriter.class.php";
//require_once "classes/validationhelper.class.php";
require_once "classes/bookingshelper.class.php";
if (!SessionHelper::isMaster()) {
    die("You don't belong here!");
}
$db = new Db();
$q = "\nSELECT \n\tb.first_name AS first_name,\n\tb.last_name AS last_name,\n\tb.email AS email\nFROM\n\tbookings b\nGROUP BY \n\temail\nORDER BY \n\temail\n";
//pr($q); // exit();
$rows = $db->getRowsByQuery($q);
$rows2 = array();
foreach ($rows as $row) {
    $rows2[] = array("name" => $row["first_name"], "surname" => $row["last_name"], "email" => $row["email"]);
}
unset($rows);
//pr($rows2); exit;
// ********************* export it now *****************9
download_send_headers("aps_emails_export_" . date("Y-m-d") . ".csv");
echo array2csv($rows2);
die;
            }
        }
        fputcsv($df, $row);
    }
    fclose($df);
    return ob_get_clean();
}
function download_send_headers($filename)
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");
    // force download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
if (isset($_POST['csv_download']) && $options['settings']['is_key_valid']) {
    download_send_headers("data_export_" . date("Y-m-d") . ".csv");
    echo array2csv($options['feeds']);
    die;
}
/* echo "<pre>";

  print_r($options);
  exit; */
Exemple #7
0
function array2csv(array &$array, $titles)
{
    if (count($array) == 0) {
        return null;
    }
    $df = fopen("file1.csv", 'w');
    fwrite($df, "");
    fputcsv($df, $titles, ';');
    foreach ($array as $row) {
        fputcsv($df, $row, ';');
    }
    fclose($df);
}
$titles = array("Категория", "Значение");
$data = array(array('Сумма всех посещений', $arrow[0]), array('Посещения библиотеки', $arrow[1]), array('Сумма Справок', $arrow[0]), array('Количество консультаций', $docs_array[3]), array('Удаленное обслуживание', $docs_array[2]), array('Искандэр', $docs_array[0]), array('Кипарис', $docs_array[1]), array('Правовые справочные системы', $docs_array[2]), array('Консультант+:', $arrow[3]), array('Правовые Базы:', $arrow[4]));
array2csv($data, $titles);
if (isset($_POST['export_csv'])) {
    file_force_download('file1.csv');
}
?>
<form action="" method="post">
    <input type="submit" name="export_csv" value="Скачать" class="form-control" id="save">

</form>
<input type="button"  value="Печать" class="form-control" id="print" >  
</form>
<script>
    $("#print").on('click', function () {


Exemple #8
0
        break;
    case 'pdf_format':
        $format_extn = '.pdf';
        break;
    case 'text_format':
    default:
        $format_extn = '.txt';
        break;
}
//pa($array_var);
download_send_headers("data_export_" . date("Y-m-d") . "{$format_extn}", $download_format);
//download_send_headers("data_export_" . date("Y-m-d") . ".html");
switch ($download_format) {
    case 'excel_format':
        if (is_array($array_var)) {
            echo array2csv($array_var);
        }
        break;
    case 'xml_format':
        if (is_array($array_var)) {
            echo array2xml($array_var);
        }
        break;
    case 'worddoc_format':
        if (is_array($array_var)) {
            echo array2worddoc($array_var);
        }
        break;
    case 'pdf_format':
        if (is_array($array_var)) {
            echo array2pdf($array_var);
Exemple #9
0
        $im->Subject = 'Search Result';
        $im->Body = 'Please find attached the search result';
        switch ($_GET['email_format'][0]) {
            case 'text_format':
                $report_op = array2text($search_class_array_all);
                $file_name = date("Y-m-d") . '_' . $class . '_report_output.txt';
                break;
            case 'pdf_format':
                $report_op = array2pdf($search_class_array_all);
                $file_name = date("Y-m-d") . '_' . $class . '_report_output.pdf';
                break;
            case 'xml_format':
                $report_op = array2xml($search_class_array_all);
                $file_name = date("Y-m-d") . '_' . $class . '_report_output.txt';
                break;
            case 'worddoc_format':
                $report_op = array2worddoc($search_class_array_all);
                $file_name = date("Y-m-d") . '_' . $class . '_report_output.doc';
                break;
            default:
                $report_op = array2csv($search_class_array_all);
                $file_name = date("Y-m-d") . '_' . $class . '_report_output.csv';
                break;
        }
        $im->addStringAttachment($report_op, $file_name);
        $im->ino_sendMail();
    }
    include_once __DIR__ . '/../template/json_search_template.inc';
    echo '</div>';
    $dbc->confirm();
}
/**
 * Output the top sellers chart.
 *
 * @access public
 * @return void
 */
function woocommerce_top_sellers()
{
    global $start_date, $end_date, $woocommerce, $wpdb;
    $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : '';
    $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : '';
    if (!$start_date) {
        $start_date = date('Ymd', strtotime(date('Ym', current_time('timestamp')) . '01'));
    }
    if (!$end_date) {
        $end_date = date('Ymd', current_time('timestamp'));
    }
    $start_date = strtotime($start_date);
    $end_date = strtotime($end_date);
    // Get order ids and dates in range
    $order_items = apply_filters('woocommerce_reports_top_sellers_order_items', $wpdb->get_results("\n\t\tSELECT order_item_meta_2.meta_value as product_id, SUM( order_item_meta.meta_value ) as item_quantity FROM {$wpdb->prefix}woocommerce_order_items as order_items\n\n\t\tLEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id\n\t\tLEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta_2 ON order_items.order_item_id = order_item_meta_2.order_item_id\n\t\tLEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID\n\t\tLEFT JOIN {$wpdb->term_relationships} AS rel ON posts.ID = rel.object_ID\n\t\tLEFT JOIN {$wpdb->term_taxonomy} AS tax USING( term_taxonomy_id )\n\t\tLEFT JOIN {$wpdb->terms} AS term USING( term_id )\n\n\t\tWHERE \tposts.post_type \t= 'shop_order'\n\t\tAND \tposts.post_status \t= 'publish'\n\t\tAND \ttax.taxonomy\t\t= 'shop_order_status'\n\t\tAND\t\tterm.slug\t\t\tIN ('" . implode("','", apply_filters('woocommerce_reports_order_statuses', array('completed', 'processing', 'on-hold'))) . "')\n\t\tAND \tpost_date > '" . date('Y-m-d', $start_date) . "'\n\t\tAND \tpost_date < '" . date('Y-m-d', strtotime('+1 day', $end_date)) . "'\n\t\tAND \torder_items.order_item_type = 'line_item'\n\t\tAND \torder_item_meta.meta_key = '_qty'\n\t\tAND \torder_item_meta_2.meta_key = '_product_id'\n\t\tGROUP BY order_item_meta_2.meta_value\n\t"), $start_date, $end_date);
    $found_products = array();
    if ($order_items) {
        foreach ($order_items as $order_item) {
            $found_products[$order_item->product_id] = $order_item->item_quantity;
        }
    }
    asort($found_products);
    $found_products = array_reverse($found_products, true);
    $found_products = array_slice($found_products, 0, 3500, true);
    reset($found_products);
    class CsvImporter
    {
        private $fp;
        private $parse_header;
        private $header;
        private $delimiter;
        private $length;
        //--------------------------------------------------------------------
        function __construct($file_name, $parse_header = true, $delimiter = ",", $length = 90000)
        {
            $this->fp = fopen($file_name, "r");
            $this->parse_header = $parse_header;
            $this->delimiter = $delimiter;
            $this->length = $length;
            //  $this->lines = $lines;
            if ($this->parse_header) {
                $this->header = fgetcsv($this->fp, $this->length, $this->delimiter);
            }
        }
        //--------------------------------------------------------------------
        function __destruct()
        {
            if ($this->fp) {
                fclose($this->fp);
            }
        }
        //--------------------------------------------------------------------
        function get($max_lines = 0)
        {
            //if $max_lines is set to 0, then get all the data
            $data = array();
            if ($max_lines > 0) {
                $line_count = 0;
            } else {
                $line_count = -1;
            }
            // so loop limit is ignored
            while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE) {
                if ($this->parse_header) {
                    foreach ($this->header as $i => $heading_i) {
                        $row_new[$heading_i] = $row[$i];
                    }
                    $data[] = $row_new;
                } else {
                    $data[] = $row;
                }
                if ($max_lines > 0) {
                    $line_count++;
                }
            }
            return $data;
        }
    }
    ?>
	<form method="post" action="">
		<p><label for="from"><?php 
    _e('From:', 'woocommerce');
    ?>
</label> <input type="text" name="start_date" id="from" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $start_date));
    ?>
" /> <label for="to"><?php 
    _e('To:', 'woocommerce');
    ?>
</label> <input type="text" name="end_date" id="to" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $end_date));
    ?>
" /> <input type="submit" class="button" value="<?php 
    _e('Show', 'woocommerce');
    ?>
" /></p>
	</form>
	<table class="bar_chart">
		<thead>
			<tr>
				<th width=15%>Кат. №</th>
				
				
				<th ><?php 
    _e('РАЗМЕР', 'woocommerce');
    ?>
</th>
				<th ><?php 
    _e('ТИП', 'woocommerce');
    ?>
</th>
				<th >Продано</th>
				<th ><?php 
    _e('ОСТАТОК', 'woocommerce');
    ?>
</th>
				<th width=15%>Цена</th>
				<th width=15%>Закуп</th>
<th width=15%>Производитель (П)</th>
<th width=15%>Назначение (Н)	</th>
<th width=15%>Применение (П)	</th>
<th width=15%>Аналог (А)
</th>
	<th width=15%>БАЛТИКА
</th>		</tr>
		</thead>
		<tbody>
			<?php 
    //$bb[]=array('TCS','Название','Продано за переод','РАЗМЕР','ТИП','ОСТАТОК');
    $a = 1;
    $max_sales = current($found_products);
    foreach ($found_products as $product_id => $sales) {
        $width = $sales > 0 ? $sales / $max_sales * 100 : 0;
        $product_title = get_the_title($product_id);
        if ($product_title) {
            $product_name = '<a href="' . get_permalink($product_id) . '">' . __($product_title) . '</a>';
            $orders_link = admin_url('edit.php?s&post_status=all&post_type=shop_order&action=-1&s=' . urlencode($product_title) . '&shop_order_status=' . implode(",", apply_filters('woocommerce_reports_order_statuses', array('completed', 'processing', 'on-hold'))));
        } else {
            $product_name = __('Product does not exist', 'woocommerce');
            $orders_link = admin_url('edit.php?s&post_status=all&post_type=shop_order&action=-1&s=&shop_order_status=' . implode(",", apply_filters('woocommerce_reports_order_statuses', array('completed', 'processing', 'on-hold'))));
        }
        $orders_link = apply_filters('woocommerce_reports_order_link', $orders_link, $product_id, $product_title);
        $rrp = get_post_meta($product_id, 'size', true);
        $rrp6 = get_post_meta($product_id, '_regular_price', true);
        $rrp1 = get_post_meta($product_id, 'tip', true);
        $rrp2 = get_post_meta($product_id, '_stock', true);
        $rrp4 = get_post_meta($product_id, 'tcs', true);
        $rrp7 = get_post_meta($product_id, 'zakup', true);
        $rrp8 = get_post_meta($product_id, 'proizvoditel', true);
        $skuu = get_post_meta($product_id, 'sku', true);
        $rrp9 = get_post_meta($product_id, 'naznachenie', true);
        $rrp10 = get_post_meta($product_id, 'primmenenie', true);
        $rrp11 = get_post_meta($product_id, 'analog', true);
        $rrp12 = get_post_meta($product_id, 'baltika', true);
        //$rrp4=$product_title;
        echo '<tr><td>' . get_post_meta($product_id, 'tcs', true) . '</td>';
        //echo '<tr><td>'.$product_title .'</td>';
        echo '<td>' . $rrp . '</td>';
        echo '<td>' . $rrp1 . '</td>';
        echo '<td width=15%><span>' . esc_html($sales) . '</span></td>';
        echo '<td>' . $rrp2 . '</td>';
        echo '<td>' . $rrp6 . '</td>';
        echo '<td>' . $rrp7 . '</td>';
        echo '<td>' . $rrp8 . '</td>';
        echo '<td>' . $rrp9 . '</td>';
        echo '<td>' . $rrp10 . '</td>';
        echo '<td>' . $rrp11 . '</td>';
        echo '<td>' . $rrp12 . '</td>';
        echo '</tr>';
        $tt = esc_html($sales);
        $bb1[] = array($skuu, $rrp4, $rrp, $rrp1, $rrp2, $rrp6, $rrp7, $rrp8, $rrp9, $rrp10, $rrp11, $rrp12);
        //$bb[]=array($rrp4,$rrp,$rrp1,(esc_html( $sales )),$rrp2,$rrp6,$rrp7,$rrp8,$rrp9,$rrp10,$rrp11);
        $y = 0;
        if ($a == 1) {
            $bb[] = array($rrp4, $rrp, $rrp1, esc_html($sales), $rrp2, $rrp6, $rrp7, $rrp8, $rrp9, $rrp10, $rrp11, $rrp12);
        } else {
            for ($x = 0; $x < count($bb); $x++) {
                if (trim($rrp4) == $bb[$x][0]) {
                    $y = 1;
                    $bb[$x][3] = $bb[$x][3] + $tt;
                    $bb[$x][4] = $bb[$x][4] + $rrp2;
                    $bb[$x][13] = $bb[$x][13] . ',' . $product_title;
                    $bb[$x][12] = $bb[$x][12] . '+' . $sales;
                }
            }
            if ($y != 1) {
                $bb[] = array($rrp4, $rrp, $rrp1, esc_html($sales), $rrp2, $rrp6, $rrp7, $rrp8, $rrp9, $rrp10, $rrp11, $rrp12);
            }
        }
        $a++;
    }
    function array2csv($input_array, $delimiter = ',', $enclosure = '"', $force_enclose = false, $crlf = "\r\n")
    {
        // filter incoming params
        if (!is_array($input_array)) {
            return false;
        }
        $delimiter = @trim($delimiter);
        $enclosure = @trim($enclosure);
        $force_enclose = @(bool) $force_enclose;
        $crlf = @(string) $crlf;
        // transform array into 2-d array of strings
        if (!is_array(array_shift(array_values($input_array)))) {
            $input_array = array($input_array);
        }
        foreach (array_keys($input_array) as $k) {
            if (!is_array($input_array[$k])) {
                return false;
            }
            foreach ($input_array[$k] as $j => $value) {
                $input_array[$k][$j] = @(string) $value;
            }
        }
        // process input array
        // RFC-compatible CSV (requires PHP 5)
        if (false === $force_enclose) {
            if (!function_exists('fputcsv')) {
                return false;
            }
            // taken from http://www.php.net/manual/ru/function.fputcsv.php
            $csv = fopen('php://temp/maxmemory:' . 1048576, 'r+');
            // try to allocate 1 MB of memory
            if (false === $csv) {
                return false;
            }
            foreach ($input_array as $row) {
                if (false === fputcsv($csv, $row, $delimiter, $enclosure)) {
                    return false;
                }
            }
            rewind($csv);
            return stream_get_contents($csv);
        } else {
            $csv_string = '';
            foreach ($input_array as $row) {
                $row_enclosed = array();
                foreach ($row as $element) {
                    $row_enclosed[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $element) . $enclosure;
                }
                $csv_string .= implode($delimiter, $row_enclosed) . $crlf;
            }
            return $csv_string;
        }
    }
    $tt = array2csv($bb, ",", '"');
    $tt1 = array2csv($bb1, ",", '"');
    //var_dump($bb);
    echo "<div style='padding: 10px;font-size: 16px;background: #F7F7F7;border: 1px #ccc;'>Продажи\t<a href='http://artibaltika/06/file.csv'>Скачать</a>\t\t</div>";
    echo "<div style='padding: 10px;font-size: 16px;background: #F7F7F7;border: 1px #ccc;'>Остатки\t<a href='http://artibaltika/06/f.csv'>Скачать</a></div>";
    $fp = fopen('/home/r/rtibal4z/rtibal4z.bget.ru/public_html/06/file.csv', "w+");
    fwrite($fp, $tt);
    fclose($fp);
    $fp1 = fopen('/home/r/rtibal4z/rtibal4z.bget.ru/public_html/06/f.csv', "w+");
    fwrite($fp1, $tt1);
    fclose($fp1);
    ?>
		</tbody>
	</table>
	<script type="text/javascript">
		jQuery(function(){
			<?php 
    woocommerce_datepicker_js();
    ?>
		});
	</script>
	<?php 
}
Exemple #11
0
 function exportData()
 {
     function build_sorter($key)
     {
         return function ($a, $b) use($key) {
             return strnatcmp($a->{$key}, $b->{$key});
         };
     }
     $permits = $this->session->userdata();
     $prod = array_merge($permits['foda']['view'], $permits['metaP']['view']);
     $finan = array_merge($permits['valorF']['view'], $permits['metaF']['view']);
     if (count($prod) + count($finan) <= 0) {
         redirect('inicio');
     }
     $this->form_validation->set_rules('graphic', 'Gráfico', 'required|numeric|greater_than_equal_to[0]');
     $this->form_validation->set_rules('all', 'Todo', 'required|numeric|in_list[0,1]');
     if (!$this->form_validation->run()) {
         redirect('inicio');
     }
     $graphic = $this->input->post('graphic');
     $all = strcmp($this->input->post('all'), "1") == 0 ? true : false;
     $graphic = $all ? $this->Dashboard_model->getAllGraphicData($graphic) : $this->Dashboard_model->getGraphicData($graphic);
     $key = $all ? 'year' : 'x';
     $data = [];
     $metric = (object) ["x_name" => "Año"];
     foreach ($graphic->series as $serie) {
         $prename = $all || strcmp($serie->aggregation, "") == 0 ? "" : $serie->aggregation . " de ";
         $metorg = $this->Metorg_model->getMetOrg(['id' => [$serie->metorg]])[0];
         $metric = $this->Metrics_model->getMetric(['id' => [$metorg->metric]])[0];
         foreach ($serie->values as $value) {
             if (!key_exists('target', $value)) {
                 continue;
             }
             $value->metric = $prename . $serie->name . " de " . $serie->org;
             $data[] = $value;
         }
     }
     $graphic->x_name = $all ? $metric->x_name : $graphic->x_name;
     $title = $graphic->title . " Periodo (" . $graphic->min_year . " - " . $graphic->max_year . ")";
     usort($data, build_sorter($key));
     download_send_headers(str_replace(" ", "_", $title) . "_" . date("d-m-Y") . ".csv");
     echo array2csv($data, $title, $graphic->x_name, $graphic->y_name, $all);
     return;
 }
<?php

session_start();
error_reporting(0);
set_time_limit(0);
require 'scrap-function.php';
if ($_POST['save']) {
    echo array2csv($_SESSION['emails'], 'sample.csv');
    unset($_SESSION['emails']);
    echo '<h3 style="color:#00FF00">Your data saved . Close this popup window </h3>';
}
?>
<form method="POST">
<input type="submit" name="save" value="Save" /> |
</form>
Exemple #13
0
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");
    // force download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
function array2csv(array &$array)
{
    if (count($array) == 0) {
        return null;
    }
    ob_start();
    $df = fopen("php://output", 'w');
    foreach ($array as $row) {
        fputcsv($df, $row);
    }
    fclose($df);
    return ob_get_clean();
}
// echo "<pre>";
//print_r($metaArray);
download_send_headers("meta_data_export_" . date("Y-m-d-H-i-s") . ".csv");
echo array2csv($metaArray);
die;
Exemple #14
0
function example()
{
    try {
        $DB = new MxOptix();
        global $app;
        $body = $app->request()->getBody();
        $body = json_decode($body, true);
        // print_r($body);
        $DB->setQuery($body['query']);
        $results = null;
        oci_execute($DB->statement);
        oci_fetch_all($DB->statement, $results, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
        // print_r($results);
        // print_r($results);
        echo array2csv($results);
        $DB->close();
    } catch (Exception $e) {
        $DB->close();
        echo 'Caught exception: ' . $e->getMessage() . "\n";
    }
}
Exemple #15
0
/**
 * Convert an array into a CSV string
 *
 * @param array $array 
 * @return string
 */
function array2csv(array $array)
{
    $lines = array();
    foreach ($array as $val) {
        $lines[] = is_array($val) ? array2csv($val) : '"' . str_replace('"', '""', $val) . '"';
    }
    return implode(",", $lines);
}
    header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
if (isset($_REQUEST["column_group"])) {
    $columns = implode(",", $_REQUEST["column_group"]);
    $sql = "select " . $columns . " from v_extensions ";
    $sql .= " where domain_uuid = '" . $domain_uuid . "' ";
    $prep_statement = $db->prepare(check_sql($sql));
    $prep_statement->execute();
    $extensions = $prep_statement->fetchAll(PDO::FETCH_ASSOC);
    unset($sql, $prep_statement);
    //	print_r($extensions);
    download_send_headers("data_export_" . date("Y-m-d") . ".csv");
    echo array2csv($extensions);
    die;
}
$columns[] = 'extension_uuid';
$columns[] = 'domain_uuid';
$columns[] = 'extension';
$columns[] = 'number_alias';
$columns[] = 'password';
$columns[] = 'accountcode';
$columns[] = 'effective_caller_id_name';
$columns[] = 'effective_caller_id_number';
$columns[] = 'outbound_caller_id_name';
$columns[] = 'outbound_caller_id_number';
$columns[] = 'emergency_caller_id_name';
$columns[] = 'emergency_caller_id_number';
$columns[] = 'directory_full_name';
                } else {
                    array_push($put, $val["nome"]);
                }
            }
            if (isset($val["cod"])) {
                array_push($put, $val["cod"]);
            } else {
                array_push($put, '--');
            }
            ksort($val["vs"]);
            foreach ($val["vs"] as $va) {
                //array_push($put,$va["v"]);
                if ($va["v"] != "") {
                    array_push($put, str_replace(".", ",", $va["v"]));
                } else {
                    array_push($put, '--');
                }
            }
            array_push($A, $put);
            $put = array();
        }
    }
    array_push($A, $put);
    return $A;
}
download_send_headers($nome . ".csv");
array2csv(ordenarV($result), $nome);
//array2csv($result,$nome);
//echo $json;
echo $nome;
die;
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");
    // force download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
function array2csv(array &$array)
{
    if (count($array) == 0) {
        return null;
    }
    ob_start();
    $df = fopen("php://output", 'w');
    fputcsv($df, array_keys(reset($array)));
    foreach ($array as $row) {
        fputcsv($df, $row);
    }
    fclose($df);
    return ob_get_clean();
}
download_send_headers("feedback_export_" . date("Y-m-d") . ".csv");
echo array2csv($allFeedbacks);
die;
                        } else if (isset($_GET['all'])) {
                            $rents = $managerDB->reqGetAllRents(); 
                            $urlDownloadCSV = "?parseall";
                        } else if (isset($_GET['number'])) {
                            $rents = $managerDB->reqGetRentsByClient($_GET['number']);
                            //download_send_headers("data_export_" . date("Y-m-d") . ".csv");
                            array2csv($rents);
                        } else if (isset($_GET['inventoryNumber'])) {
                            $rents = $managerDB->reqGetRentsByInventory($_GET['inventoryNumber']);
                            array2csv($rents);
                        } else if ( isset($_GET['day']) && isset($_GET['month']) && isset($_GET['year']) ) {
                            $rents = $managerDB->reqGetRentsByDate($_GET['year']."-".$_GET['month']."-".$_GET['day']);
                            array2csv($rents);                              
                        } else if(isset($_GET['parseall'])){
                            $rents = $managerDB->reqGetAllRents();
                            array2csv($rents); 
                        }
                        
                        if ( !is_null($rents) ) {
                            echo "<a href='".$urlDownloadCSV."'>Save to CSV</a>";
                            echo "<table border='1'>";

                            foreach($rents as $rent) {
                                echo "<tr>";
                                echo "<td>".$rent->shiftDate."</td>";
                                echo "<td>".$rent->inventoryNumber."</td>";
                                echo "<td>".$rent->inventoryModel."</td>";
                                echo "<td>".$rent->clientPhone."</td>";
                                echo "<td>".$rent->clientName."</td>";
                                echo "<td>".$rent->expense."</td>";
                                echo "</tr>";
            $array[$key] = encode_items($value);
        } else {
            $array[$key] = mb_convert_encoding($value, 'Windows-1252', 'UTF-8');
        }
    }
    return $array;
}
function download_send_headers($filename)
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    //header('Content-Type: text/html; charset=utf-8');
    header('Content-Type: text/html; charset=ANSI');
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");
    // force download
    //header("Content-Type: application/force-download");
    //header("Content-Type: application/octet-stream");
    //header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    //header("Content-Transfer-Encoding: binary");
    //header("Content-Transfer-Encoding: UTF-8");
    header("Content-Transfer-Encoding: ANSI");
}
download_send_headers($nome . ".csv");
//die(var_dump($result));
array2csv($result, $nome);
echo $nome;
die;
Exemple #21
0
<?php

require 'functions.php';
include 'connect.php';
$sql = "select * from em_animal order by datCreat desc ";
$res = $DB->query($sql);
if ($res) {
    $arr = $res->fetchAll(PDO::FETCH_ASSOC);
    download_send_headers("qrv_export_" . date("Y-m-d") . ".csv");
    echo array2csv($arr);
    die;
}
        return null;
    }
    ob_start();
    $df = fopen("php://output", 'w');
    //fputcsv($df, array_keys(reset($array)));
    foreach ($array as $row) {
        fputcsv($df, $row, ";");
    }
    fclose($df);
    return ob_get_clean();
}
function download_send_headers($filename)
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");
    // force download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
download_send_headers("data_export_" . date("Y-m-d_H_i_s") . ".csv");
$data = translate($data, $_SESSION['lang'] ? $_SESSION['lang'] : 'ru');
echo iconv("utf-8", "windows-1251", array2csv($data));
unlink($tmp);
die;
Exemple #23
0
function start_next_program()
{
    global $dbc, $si;
    $p = new sys_program();
    $p_toStart = $p->findBy_status('Initiated');
    if (!empty($p_toStart)) {
        foreach ($p->field_a as $key => $value) {
            $p->{$value} = $p_toStart->{$value};
        }
        //update the status to inprogress
        $p->status = 'inprogress';
        $p->save();
        $dbc->confirm();
        $class = $p->class;
        ${$class} = new $class();
        if ($p_toStart->request_type == 'REPORT') {
            $search_class_obj_all = ${$class}->findBySql(base64_decode($p_toStart->report_query));
            $search_class_array_all = json_decode(json_encode($search_class_obj_all), true);
            if (!empty($p_toStart->op_email_address)) {
                //send email
                $im = new inomail();
                $im->FromName = $si->site_name;
                $email_a = explode(',', $p_toStart->op_email_address);
                foreach ($email_a as $em_k => $email_v) {
                    $im->addAddress($email_v);
                }
                $im->addReplyTo($si->email, 'Search Output');
                $im->Subject = 'Search Result';
                $im->Body = 'Please find attached the search result';
                switch ($p_toStart->op_email_format) {
                    case 'text_format':
                        $report_op = array2text($search_class_array_all);
                        $file_name = date("Y-m-d") . '_' . $class . '_report_output.txt';
                        break;
                    case 'pdf_format':
                        $report_op = array2pdf($search_class_array_all);
                        $file_name = date("Y-m-d") . '_' . $class . '_report_output.pdf';
                        break;
                    case 'xml_format':
                        $report_op = array2xml($search_class_array_all);
                        $file_name = date("Y-m-d") . '_' . $class . '_report_output.txt';
                        break;
                    case 'worddoc_format':
                        $report_op = array2worddoc($search_class_array_all);
                        $file_name = date("Y-m-d") . '_' . $class . '_report_output.doc';
                        break;
                    default:
                        $report_op = array2csv($search_class_array_all);
                        $file_name = date("Y-m-d") . '_' . $class . '_report_output.csv';
                        break;
                }
                $im->addStringAttachment($report_op, $file_name);
                try {
                    $im->ino_sendMail();
                    $p->message = "Program {$p->program_name} is sucessfully completed <br>" . execution_time();
                    $p->status = 'Completed';
                } catch (Exception $e) {
                    $p->status = 'Error';
                }
                $p->save();
            }
        } else {
            try {
                $result = call_user_func(array(${$class}, $p->program_name), $p->parameters);
                $result_message = is_array($result) ? $result[0] : $result;
                $result_output = is_array($result) ? $result[1] : null;
                $p->message = "Program {$p->program_name} is sucessfully completed <br>" . $result_message . '<br>' . execution_time();
                $p->status = 'Completed';
                try {
                    if (!empty($result_output)) {
                        $op_file_name = $p->program_name . '_' . time() . '.xls';
                        $module_name = $class::$module;
                        $file_path = HOME_DIR . "/files/outputs/modules/{$module_name}/{$p->program_name}/{$op_file_name}";
                        $file = fopen($file_path, 'w');
                        $headerData = [];
                        foreach ($result_output[0] as $key => $value) {
                            array_push($headerData, $key);
                        }
                        fputcsv($file, $headerData);
                        foreach ($result_output as $obj) {
                            $rowData = [];
                            foreach ($obj as $key => $value) {
                                array_push($rowData, $value);
                            }
                            fputcsv($file, $rowData);
                        }
                        fclose($file);
                        $p->output_path = "/files/outputs/modules/{$module_name}/{$p->program_name}/{$op_file_name}";
                    }
                } catch (Exception $e) {
                    $p->output_path = null;
                }
                $p->save();
            } catch (Exception $e) {
                $p->status = 'Failed';
                $p->message = "<br> Program failed @ start_program " . __LINE__ . '<br>' . $e->getMessage();
                $p->save();
            }
        }
        $dbc->confirm();
    } else {
        sleep(5);
    }
    execution_time();
    unset($p_toStart);
    unset($p);
}
Exemple #24
0
    }
}
$badge_prints[$badge_page] = $last_page_badges;
$programme = $forum->genAgenda('2010', true, true);
$code_salle[8] = "LA1";
$code_salle[9] = "LA2";
$code_salle[10] = "S1";
$code_salle[11] = "S3";
$code_salle[12] = "SAB";
$code_salle[13] = "SCD";
$code_salle[14] = "S2";
//var_dump( $programme);die;
if ($action == 'export') {
    header('Content-type: text/plain');
    header('Content-disposition: attachment; filename=inscription_forum_php.csv');
    echo array2csv($badges_export);
    exit;
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style media="all">
@page {
  size: A3;
  margin: 5mm;
}

td {
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");
    // force download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}
include "class.MySQL.php";
$conn = new MySQL();
$arquivo = 'planilha_download_saude_na_copa.xls';
$titulo = array("ID_REG_SEQ", "ID_USUARIO", "APELIDO", "IDADE", "SEXO", "EMAIL", "IDIOMA", "DT_CADASTRO", "DT_REGISTRO_DIA", "DT_REGISTRO_HORA", "LOC_REGISTRO", "REGIAO", "EQUIPAMENTO", "LAT", "LONG", "STATUS", "FEBRE", "TOSSE", "DORGARGANTA", "FALTAR", "NAUSEA", "DIARREIA", "ARTRALGIA", "CEFALEIA", "HEMORRAGIA", "EXANTEMA", "CONTATO", "SERVSAUDE", "CADASTRO", "SINTOMA", "SIND_DIA", "SIND_RES", "SIND_EXA", "TOTAL");
//, "ATUALIZA");
$sql = "SELECT ID_REG_SEQ, ID_USUARIO ,APELIDO,IDADE, SEXO, EMAIL, IDIOMA , DT_CADASTRO,\nDT_REGISTRO_DIA, DT_REGISTRO_HORA,   LOC_REGISTRO  ,  REGIAO , EQUIPAMENTO,\nLATITUDE ,LONGITUDE, STATUS, FEBRE, TOSSE, DORGARGANTA, FALTAR, NAUSEA,\nDIARREIA, ARTRALGIA, CEFALEIA, HEMORRAGIA, EXANTEMA, CONTATO, SERVSAUDE,\nCADASTRO, SINTOMA, SIND_DIA, SIND_RES, SIND_EXA, total FROM `csv_leve` inner join lastinsert on ultimo = csv_leve.ID_REG_SEQ";
$conn->ExecuteSQL($sql);
$array[0] = $titulo;
$array[1] = $conn->ArrayResults();
$recife = new DateTimeZone("America/Recife");
$HoraBrasilia = new DateTime();
$HoraBrasilia->setTimezone($recife);
$Hora = $HoraBrasilia->format("H_i_s");
//download_send_headers("SaudeNaCopa_" . date("Y-m-d-H-i-s") . ".csv");
download_send_headers("saudenacopa_" . date("Y_m_d") . "_" . $Hora . ".csv");
echo array2csv($array, $conn);
die;
$total_sentimento = $conn->ArrayResult();
$total_sentimento["total"];
$sql = "UPDATE total_usuario_sentimento SET total= " . $total["total"];
//$conn->ExecuteSQL($sql);
$listagem = $total["total"] - $total_sentimento["total"];
//echo "<br>";
$titulo = array("ID_REG_SEQ", "ID_USUARIO", "APELIDO", "IDADE", "SEXO", "EMAIL", "IDIOMA", "DT_CADASTRO", "DT_REGISTRO_DIA", "DT_REGISTRO_HORA", "LOC_REGISTRO", "REGIAO", "EQUIPAMENTO", "LAT", "LONG", "STATUS", "FEBRE", "TOSSE", "DORGARGANTA", "FALTAR", "NAUSEA", "DIARREIA", "ARTRALGIA", "CEFALEIA", "HEMORRAGIA", "EXANTEMA", "CONTATO", "SERVSAUDE", "CADASTRO", "SINTOMA", "CONTAGEM", "SIND_DIA", "SIND_RES", "SIND_EXA", "ATUALIZA");
/*
$sql = "SELECT u.id, u.apelido, u.idade, u.sexo, u.email , u.data_hora, 
u.hash, u.gcmid, u.idioma, us.data_cadastro, us.pontuacao,
us.latitude, us.longitude, c.nome, us.campo1, us.campo2, us.campo3,
us.campo4, us.campo5, us.campo6, us.campo7, us.campo8, us.campo9,
us.campo10, us.campo11, us.campo12
FROM usuarios u
INNER JOIN usuario_sentimento us ON us.usuario_id = u.id
INNER JOIN cidade c ON us.cidade_id = c.id";
*/
$sql = "SELECT \nus.id,\nus.usuario_id as usuario_id, u.apelido, \nu.idade, u.sexo, \nu.email ,u.idioma, \nus.data_cadastro as data_cadastro,\nDate(us.data_cadastro) as data_cadastro_dia,\nTime(us.data_cadastro) as data_cadastro_hora,\nus.cidade_id as cidade,\nus.cidade_regiao_metro as regiao,\nu.device,\nus.latitude as latitude, us.longitude as longitude, us.sentimento as sentimento,\nus.campo1 as campo1, us.campo2 as campo2, us.campo3 as campo3,\nus.campo4 as campo4, us.campo5 as campo5, us.campo6 as campo6, \nus.campo7 as campo7, us.campo8 as campo8, us.campo9 as campo9,\nus.campo10 as campo10, us.campo11 as campo11, us.campo12 as campo12, \nu.data_hora as data_hora\nFROM usuarios u\nINNER JOIN usuario_sentimento us ON us.usuario_id = u.id\norder by us.usuario_id, us.data_cadastro\nlimit 0,30";
//limit " . $total_sentimento["total"] . "," . $listagem;
$conn->ExecuteSQL($sql);
$array[0] = $titulo;
$array[1] = $conn->ArrayResults();
$recife = new DateTimeZone("America/Recife");
$HoraBrasilia = new DateTime();
$HoraBrasilia->setTimezone($recife);
$Hora = $HoraBrasilia->format("H_i_s");
$arquivo = "saudenacopa.csv";
echo array2csv($array, $conn, $arquivo);
download_send_headers($arquivo);
//download_send_headers("saudenacopa_" . date("Y_m_d") . "_" . $Hora . ".csv");
die;
                 $item->author = 'PmL';
             }
             $item->link = $link . '&' . $log['pmlo'];
             $item->guid = $link . '&' . $log['pmlo'];
             $item->descriptionTruncSize = 500;
             $item->descriptionHtmlSyndicated = true;
             $rss->addItem($item);
         }
     }
     $rss->outputFeed($tz, $format);
     break;
 case 'CSV':
     header("Content-Transfer-Encoding: binary");
     header("Content-Disposition: attachment;filename=PimpMyLog_" . get_slug($file_id) . "_" . date("Y-m-d-His") . '.csv');
     header("Content-type: application/vnd.ms-excel; charset=UTF-16LE");
     echo chr(255) . chr(254) . mb_convert_encoding(array2csv($logs['logs']), 'UTF-16LE', 'UTF-8');
     break;
 case 'XML':
     header('Content-type: application/xml', true);
     $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
     $xml .= '<pml>';
     $xml .= generate_xml_from_array($logs, 'log');
     $xml .= '</pml>';
     echo $xml;
     break;
 case 'JSONPR':
     header('Content-type: application/json', true);
     if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
         echo json_encode($logs, JSON_PRETTY_PRINT);
     } else {
         echo json_indent(json_encode($logs));
    // caso receba a requisicao de saida em arquivo
    if ($output_path == 'arquivo') {
        $output_path = __DIR__ . '/relatorios/arquivos/';
    }
}
if ($data_csv != '') {
    $data_csv = json_decode($data_csv);
    // se nao receber path, gera php
    if ($output_path == '') {
        download_send_headers($filename);
        print array2csv($data_csv);
    } else {
        // se receber, gera arquivo e baixa
        //
        $output_web = "http://" . $_SERVER['HTTP_HOST'] . explode('baixar-csv.php', $_SERVER['PHP_SELF'])[0] . 'relatorios/arquivos/' . $filename;
        print array2csv($data_csv, $output_path . $filename);
        //print "<script>window.location='" . $output_web . "';</script>";
        //print "<a href='" . $output_web . "'><h3 id='exportarCSVPost' class='csv' data_filename='relatorio_inscritos_setorial_estado'></h3></a>";
        download_send_headers($filename, $output_path . $filename);
    }
    die;
} else {
    ?>
<!doctype html>
<html lang="pt-BR">
<head>
<title></title>
<link rel="stylesheet" href="admin.css">  
<script type="text/javascript" src="../../../wp-includes/js/jquery/jquery.js?ver=1.11.1"></script>
<script type="text/javascript">
(function($) {
Exemple #29
0
            if ($k == 'Frequência' && $v < 75) {
                unset($array[$key]);
            }
        }
    }
    // print_r($array);
    $nomeArquivo .= "_certificado";
} else {
    if (isset($_GET['frequencia'])) {
        $nomeArquivo .= "_frequencia";
    }
}
// print_r($array);
// download_send_headers($nomeArquivo . ".csv");
echo "<pre>";
echo array2csv($array);
echo "</pre>";
die;
function calcula_frequencia($array, $data, $ev)
{
    // print_r($array);
    // print_r($data);
    $frequencia = 0;
    $frequenciaTotal = 0;
    $cargaHoraria = 0;
    $horarios = array();
    $pcpf = $array['Número do Documento'];
    // echo $pcpf."<br>";
    $eid = $ev['eid'];
    // print_r($ev);
    $query = "SELECT data from presenca where pcpf = '{$pcpf}' and eid = '{$eid}'";
Exemple #30
0
    function array2csv(array &$array, $titles)
    {
        if (count($array) == 0) {
            return null;
        }
        ob_start();
        $df = fopen("php://output", 'w');
        fputcsv($df, $titles, ';');
        foreach ($array as $row) {
            fputcsv($df, $row, ';');
        }
        fclose($df);
        return ob_get_clean();
    }
    download_send_headers("data_export.csv");
    echo array2csv($csv_data, $titles);
    die;
}
?>

<h3>Експорт</h3>
<?php 
if ($data['unchecked_indexes'] == 0) {
    echo "У вас немає неперевірених даних";
} else {
    ?>
<strong>Неперевірених показників: <?php 
    echo $data['unchecked_indexes'];
    ?>
</strong><br>
    <form class="form-inline" role="form" method="post" action="">