Beispiel #1
6
 protected function parse_file($file)
 {
     $csv = new \parseCSV();
     $csv->delimiter = ";";
     $csv->parse($file);
     if ($this->tag_ok) {
         $tableHead = "<div  class='table-respond'><table><thead><tr><th>Titre</th><th>Album</th></tr></thead><tbody>";
     } else {
         $tableHead = "<div  class='table-respond'><table><thead><tr><th>Titre</th><th>Artiste</th><th>Album</th></tr></thead><tbody>";
     }
     $tableEnd = "</tbody></table></div>";
     $tableBody = "";
     foreach ($csv->data as $key => $row) {
         $annee = "";
         $groupe = "";
         if ($this->tag_ok) {
             if (isset($row['Groupe']) && strpos(html_entity_decode($row['Groupe']), html_entity_decode($this->tag_name)) !== false) {
                 if ($row['Année']) {
                     $annee = "<span class='playlist_year'> (" . $row['Année'] . ")</span>";
                 }
                 $tableBody .= "<tr><td>" . $row['Titre'] . "</td><td>" . $row['Album'] . $annee . "</td></tr>";
             }
         } else {
             if ($row['URL']) {
                 if ($row['Groupe']) {
                     $groupe = "<a href='" . $row['URL'] . "' title='" . $row['URL'] . "' target='_blank'>" . $row['Groupe'] . "</a>";
                 } else {
                     $row['Titre'] = "<a href='" . $row['URL'] . "' title='" . $row['URL'] . "' target='_blank'>" . $row['Titre'] . "</a>";
                 }
             } else {
                 $groupe = $row['Groupe'];
             }
             if ($row['Année']) {
                 $annee = "<span class='playlist_year'> (" . $row['Année'] . ")</span>";
             }
             $tableBody .= "<tr><td>" . $row['Titre'] . "</td><td>" . $groupe . "</td><td>" . $row['Album'] . $annee . "</td></tr>";
         }
     }
     $ret = $tableHead . $tableBody . $tableEnd;
     return $ret;
 }
 public function read()
 {
     global $default_charset;
     $filePath = $this->getFilePath();
     $status = $this->createTable();
     if (!$status) {
         return false;
     }
     $csv = new parseCSV();
     $csv->delimiter = $this->request->get('delimiter');
     $csv->parse($filePath);
     $data = $csv->data;
     $fieldMapping = $this->request->get('field_mapping');
     if (!$this->request->get('has_header')) {
         $firstRow = array_keys($data[0]);
         array_unshift($data, $firstRow);
     }
     foreach ($data as $row_data) {
         $row_data_index = array_values($row_data);
         $mappedData = array();
         $allValuesEmpty = true;
         foreach ($fieldMapping as $fieldName => $index) {
             $fieldValue = $row_data_index[$index];
             $mappedData[$fieldName] = $fieldValue;
             if ($this->request->get('file_encoding') != $default_charset) {
                 $mappedData[$fieldName] = $this->convertCharacterEncoding($fieldValue, $this->request->get('file_encoding'), $default_charset);
             }
             if (!empty($fieldValue)) {
                 $allValuesEmpty = false;
             }
         }
         if ($allValuesEmpty) {
             continue;
         }
         $fieldNames = array_keys($mappedData);
         $fieldValues = array_values($mappedData);
         $this->addRecordToDB($fieldNames, $fieldValues);
     }
 }
 /**
  * @param $inputData
  * @return MerchantDataListing[]
  */
 public function processData($inputData)
 {
     $inputData = mb_convert_encoding($inputData, "utf-8", "windows-1252");
     $csv = new \parseCSV();
     //$csv->encoding('Windows-1252', 'UTF-8');
     $csv->delimiter = "\t";
     $csv->parse($inputData);
     $itemList = array();
     foreach ($csv->data as $row) {
         $item = new MerchantDataListing();
         $item->setData($row);
         $itemList[] = $item;
     }
     return $itemList;
 }
Beispiel #4
1
function csvDataToMemcache($csvList, $csvDir, $memIP, $memPort)
{
    $memcached = new Memcache();
    $memcached->connect($memIP, $memPort);
    foreach ($csvList as $key => $value) {
        $csvObj = new parseCSV();
        $csvObj->auto($csvDir . '/' . $value);
        list($fileName, $fileType) = explode('.', $value);
        $memcached->set($fileName, $csvObj->data, MEMCACHE_COMPRESSED, 0);
        //debug info
        //echo "<br/>--------------------------------------------$fileName.csv to memcache-------------------------------------------<br/>";
        print_r($memcached->get($fileName));
    }
    $memcached->close();
    echo "success";
}
Beispiel #5
1
 public static function getCSV($file_path, $limit = false, $offset = false)
 {
     if (file_exists($file_path) && is_readable($file_path)) {
         if (!class_exists('parseCSV')) {
             require_once GMEMBER_DIR . '/assets/libs/parsecsv-for-php/parsecsv.lib.php';
         }
         $csv = new parseCSV();
         $csv->encoding('UTF-16', 'UTF-8');
         if ($offset) {
             $csv->offset = $offset;
         }
         if ($limit) {
             $csv->limit = $limit;
         }
         $csv->auto($file_path);
         return array('titles' => $csv->titles, 'data' => $csv->data);
     }
     return false;
     return array('titles' => array(), 'data' => array());
 }
 function ImportCsv($file_lines, $delims = array(";", ",", "\t"), $quotes = array('"', "'"))
 {
     function maxChar($chars, $testString)
     {
         $max_count = 0;
         $the_char = count($chars) > 0 ? $chars[0] : " ";
         foreach ($chars as $char) {
             $new_count = substr_count($testString, $char);
             if ($new_count > $max_count) {
                 $max_count = $new_count;
                 $the_char = $char;
             }
         }
         return $the_char;
     }
     $test_line = $file_lines[0];
     //
     // Detect the most probable delimiter.
     //
     $delim = maxChar($delims, $test_line);
     $quote = maxChar($quotes, $test_line);
     //
     // Re-Conncat the file-lines
     //
     $input = implode("\n", $file_lines) . "\n";
     //
     // Setup and run the parser
     //
     include "lib/parsecsv.lib.php";
     $csv = new parseCSV();
     $csv->delimiter = $delim;
     $csv->enclosure = $quote;
     $csv->file_data =& $input;
     $this->data = $csv->parse_string();
     //
     // Convert the array to addresses
     //
     $this->convertToAddresses();
 }
 function index()
 {
     if (!empty($this->data) && !empty($_POST['submit'])) {
         $string = explode(",", trim($this->data['InventoryMaster']['all_item']));
         $prsku = $string[0];
         if (!empty($string[1])) {
             $prname = $string[1];
         }
         if (!empty($prsku) && !empty($prname)) {
             $conditions = array('InventoryMaster.category LIKE' => '%' . $prname . '%', 'InventoryMaster.category LIKE' => '%' . $prsku . '%');
             $this->paginate = array('limit' => 1000, 'totallimit' => 2000, 'order' => 'InventoryMaster.id  ASC', 'conditions' => $conditions);
         }
         if (!empty($prsku)) {
             $conditions = array('OR' => array('InventoryMaster.product_code LIKE' => "%{$prsku}%", 'InventoryMaster.category LIKE' => "%{$prsku}%"));
             $this->paginate = array('limit' => 1000, 'totallimit' => 2000, 'order' => 'InventoryMaster.id  ASC', 'conditions' => $conditions);
         }
         $this->InventoryMaster->recursive = 1;
         $this->set('inventorymasters', $this->paginate());
     } else {
         if (!empty($_POST['checkid']) && !empty($_POST['exports'])) {
             // echo 'dfbgghbfg';die();
             $checkboxid = $_POST['checkid'];
             App::import("Vendor", "parsecsv");
             $csv = new parseCSV();
             $filepath = "C:\\Users\\Administrator\\Downloads" . "inventorymasterdb.csv";
             $csv->auto($filepath);
             $this->set('inventorymasters', $this->InventoryMaster->find('all', array('conditions' => array('InventoryMaster.id' => $checkboxid))));
             $this->layout = null;
             $this->autoLayout = false;
             Configure::write('debug', '2');
         } else {
             $this->InventoryMaster->recursive = 1;
             //$users = $this->InventoryMaster->User->find('list');
             $this->paginate = array('limit' => 1000, 'totallimit' => 2000, 'order' => 'InventoryMaster.id  ASC');
             $this->set('inventorymasters', $this->paginate());
         }
     }
 }
 public function parse_attendee_list($csv_text)
 {
     $csv = new parseCSV();
     $csv->delimiter = "\t";
     $csv->data = $csv->parse_string($csv_text);
     return $csv->data;
 }
Beispiel #9
0
function csvFileread($target_file)
{
    # include parseCSV class.
    require_once 'parsecsv.lib.php';
    # create new parseCSV object.
    $csv = new parseCSV();
    # Parse '_books.csv' using automatic delimiter detection...
    $csv->auto("uploads/{$target_file}.csv");
    //$csv->auto("abc.csv");
    # ...or if you know the delimiter, set the delimiter character
    # if its not the default comma...
    $csv->delimiter = "\t";
    # tab delimited
    # ...and then use the parse() function.
    // $csv->parse('_books.csv');
    # Output result.
    echo "hello";
    print_r($csv->data);
    $i = 0;
    foreach ($csv->data as $key => $row) {
        print_r($row);
        if ($i == 5) {
            die;
        }
        $i++;
    }
}
Beispiel #10
0
function parseFind($csvFile, $afm, $surname)
{
    // init vars
    $empOffset = 5;
    $anadrData = [];
    // parse csv & find employee
    $csv = new parseCSV();
    $csv->encoding('iso8859-7', 'UTF-8');
    $csv->delimiter = ";";
    $csv->heading = false;
    // find employee T.M.
    $csv->offset = $empOffset;
    $condition = '8 is ' . $afm . ' AND 1 contains ' . grstrtoupper($surname);
    $csv->conditions = $condition;
    $csv->parse($csvFile);
    $parsed = $csv->data;
    // enhanced check of surname (instead of 'contains' in fullname)
    if ($parsed) {
        $tmp = explode(' ', $parsed[0][1]);
        $fileSurname = $tmp[0];
        if (strcmp(grstrtoupper($surname), $fileSurname) != 0) {
            return ['parsed' => [], 'month' => []];
        }
    }
    // find month
    $csv->offset = 1;
    $csv->conditions = '19 contains ΜΙΣΘΟΔΟΣΙΑ';
    $csv->parse($csvFile);
    //$csv->fields =[19];
    $data = $csv->data;
    $tmp = explode(' ', $data[0][19]);
    $month = $tmp[2] . '_' . $tmp[3];
    // find anadromika (if any)
    $csv->offset = $empOffset;
    $csv->conditions = '';
    $csv->parse($csvFile);
    $data = $csv->data;
    $i = $foundFrom = $foundTo = 0;
    foreach ($data as $row) {
        if (array_key_exists('8', $row) && $afm == $row[8] && !$foundFrom) {
            $foundFrom = $i;
        }
        if ($foundFrom && !$foundTo && array_key_exists('8', $row)) {
            if ($row[8] != '' && $row[8] != $afm) {
                $foundTo = $i - 1;
            }
        }
        $i++;
    }
    $tempData = array_slice($data, $foundFrom, $foundTo - $foundFrom + 1);
    foreach ($tempData as $line) {
        if ($line[10] == 'ΑΝΑΔΡΟΜΙΚΑ') {
            $anadrData = $line;
        }
    }
    if (count($anadrData) > 0) {
        array_push($parsed, $anadrData);
    }
    return ['parsed' => $parsed, 'month' => $month];
}
 function index()
 {
     if (!empty($this->data) && !empty($_POST['submit'])) {
         $string = explode(",", trim($this->data['EbayenglishListing']['all_item']));
         $prsku = $string[0];
         if (!empty($string[1])) {
             $prname = $string[1];
         }
         if (!empty($prsku) && !empty($prname)) {
             $conditions = array('EbayenglishListing.title LIKE' => '%' . $prname . '%', 'EbayenglishListing.title LIKE' => '%' . $prsku . '%');
             $this->paginate = array('limit' => 1000, 'totallimit' => 2000, 'order' => 'EbayenglishListing.sku  id', 'conditions' => $conditions);
         }
         if (!empty($prsku)) {
             $conditions = array('OR' => array('EbayenglishListing.title LIKE' => "%{$prsku}%", 'EbayenglishListing.sku LIKE' => "%{$prsku}%"));
             $this->paginate = array('limit' => 1000, 'totallimit' => 2000, 'order' => 'EbayenglishListing.id  ASC', 'conditions' => $conditions);
         }
         $this->set('ebayenglishlistings', $this->paginate());
     } else {
         if (!empty($_POST['checkid']) && !empty($_POST['exports'])) {
             $checkboxid = $_POST['checkid'];
             App::import("Vendor", "parsecsv");
             $csv = new parseCSV();
             $filepath = "C:\\Users\\Administrator\\Downloads" . "ebayenglishlistings.csv";
             $csv->auto($filepath);
             $this->set('ebayenglishlistings', $this->EbayenglishListing->find('all', array('conditions' => array('EbayenglishListing.id' => $checkboxid))));
             $this->layout = null;
             $this->autoLayout = false;
             Configure::write('debug', '2');
         } else {
             $this->EbayenglishListing->recursive = 1;
             $this->paginate = array('limit' => 1000, 'totallimit' => 2000, 'order' => 'EbayenglishListing.id  ASC');
             $this->set('ebayenglishlistings', $this->paginate());
         }
     }
 }
Beispiel #12
0
 public function upload()
 {
     ini_set("auto_detect_line_endings", true);
     ini_set('memory_limit', '512M');
     set_time_limit(600);
     require_once ROOT . DS . 'vendor' . DS . 'parsecsv.lib.php';
     try {
         $numberListTable = TableRegistry::get('NumberLists');
         $numberTable = TableRegistry::get('Numbers');
         // Generate temp file name
         $uploadFullPath = TMP . DS . Text::uuid();
         // Move file to temp location
         if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadFullPath)) {
             throw new \Exception('Cannot copy file to tmp location');
         }
         $dateTimeUtc = new \DateTimeZone('UTC');
         $now = new \DateTime('now', $dateTimeUtc);
         // Create new list
         $newNumberListData = ['list_name' => $this->request->data['list_name'], 'list_description' => $this->request->data['list_description'], 'create_datetime' => $now, 'update_datetime' => $now];
         $numberList = $numberListTable->newEntity($newNumberListData);
         $numberListTable->save($numberList);
         // Get the data from the file
         $csv = new \parseCSV();
         $csv->heading = false;
         $csv->auto($uploadFullPath);
         if (count($csv->data) == 0) {
             throw new \Exception('File is empty');
         }
         $newNumberData = [];
         foreach ($csv->data as $row) {
             $responseM360 = $this->M360->optInTfn($row[1]);
             //                $response['d'][] = $responseM360;
             $newNumberData = ['number_list_id' => $numberList->number_list_id, 'country_code' => $row[0], 'phone_number' => $row[1], 'opt_in_tfn' => (bool) $responseM360['Message360']['OptIns']['OptIn']['Status'] === 'updated', 'add_datetime' => $now];
             $number = $numberTable->newEntity($newNumberData);
             $numberTable->save($number);
         }
         //            $numbers = $numberTable->newEntity($newNumberData);
         //
         //            $numberTable->connection()->transactional(function () use ($numberTable, $numbers) {
         //                foreach ($numbers as $number) {
         //                    $numberTable->save($number, ['atomic' => false]);
         //                }
         //            });
         unlink($uploadFullPath);
         $response['i'] = $newNumberData;
         $response['status'] = 1;
     } catch (\Excaption $ex) {
         $response['status'] = 0;
         $response['message'] = $ex->getMessage();
     }
     $this->set(compact('response'));
     $this->set('_serialize', ['response']);
 }
 /**
  * Renders the CSV.
  *
  * @return void
  */
 public function process()
 {
     $params = $this->gp;
     $exportParams = Tx_Formhandler_StaticFuncs::getSingle($this->settings, 'exportParams');
     if (!is_array($exportParams)) {
         $exportParams = t3lib_div::trimExplode(',', $exportParams);
     }
     //build data
     foreach ($params as $key => &$value) {
         if (is_array($value)) {
             $value = implode(',', $value);
         }
         if (count($exportParams) > 0 && !in_array($key, $exportParams)) {
             unset($params[$key]);
         }
         $value = str_replace('"', '""', $value);
     }
     // create new parseCSV object.
     $csv = new parseCSV();
     $csv->output('formhandler.csv', $data, $params);
     die;
 }
Beispiel #14
0
 public function saveimport()
 {
     $response = array("status" => 0, "msg" => "Gagal simpan data");
     include APPPATH . "libraries/parsecsv.lib.php";
     // echo "<pre>";
     // print_r($_FILES);
     // echo "</pre>";
     if (isset($_FILES['inputFile']) && !empty($_FILES['inputFile']['name'])) {
         $files = $_FILES['inputFile'];
         $allowed_extension = array('csv');
         $extension = end(explode('.', strtolower($files['name'])));
         if (in_array($extension, $allowed_extension)) {
             $newname = date('YmdHis') . "_import_cpns.csv";
             if (move_uploaded_file($files['tmp_name'], _ROOT . "files/import/{$newname}")) {
                 if (file_exists(_ROOT . "files/import/{$newname}")) {
                     $response = array("status" => 0, "msg" => "sukses simpan data");
                     $destination = _ROOT . "files/import/{$newname}";
                     $csv = new parseCSV();
                     $data = $csv->auto($destination);
                     $datashipping = array();
                     foreach ((array) $csv->data as $index => $row) {
                         $save = $this->pengadaan_model->simpanDataCPNSimport($row);
                     }
                     $response = array("status" => 1, "msg" => "Sukses import file");
                 }
             }
         } else {
             $response = array("status" => 0, "msg" => "Ekstensi file harus .csv");
         }
     }
     // echo "<pre>";
     // print_r($response);
     // echo "</pre>";
     echo json_encode($response);
     exit;
 }
<?php

header('Content-Type: application/json');
require_once '../parsecsv-for-php/parsecsv.lib.php';
$csv = new parseCSV();
$csv->parse('../../../00_ADMIN_CSV_FOLDER/bodytype_service_pricing_minutes.csv');
echo json_encode($csv->data);
Beispiel #16
0
function gigpress_import()
{
    // Deep breath
    global $wpdb, $gpo;
    // We've just uploaded a file to import
    check_admin_referer('gigpress-action');
    $upload = wp_upload_bits($_FILES['gp_import']['name'], null, file_get_contents($_FILES['gp_import']['tmp_name']));
    if (!$upload['error']) {
        // The file was uploaded, so let's try and parse the mofo
        require_once WP_PLUGIN_DIR . '/gigpress/lib/parsecsv.lib.php';
        // This is under MIT license, which ain't GNU, but was else is new? Don't tell on me!
        $csv = new parseCSV();
        $csv->parse($upload['file']);
        if ($csv->data) {
            // Looks like we parsed something
            $inserted = array();
            $skipped = array();
            $duplicates = array();
            foreach ($csv->data as $key => $show) {
                // Check to see if we have this artist
                $artist_exists = $wpdb->get_var("SELECT artist_id FROM " . GIGPRESS_ARTISTS . " WHERE artist_name = '" . mysql_real_escape_string($show['Artist']) . "'");
                if (!$artist_exists) {
                    // Can't find an artist with this name, so we'll have to create them
                    $new_artist = array('artist_name' => gigpress_db_in($show['Artist']));
                    $wpdb->insert(GIGPRESS_ARTISTS, $new_artist);
                    $show['artist_id'] = $wpdb->insert_id;
                } else {
                    $show['artist_id'] = $artist_exists;
                }
                if ($show['Tour']) {
                    // Check to see if we have this tour
                    $tour_exists = $wpdb->get_var("SELECT tour_id FROM " . GIGPRESS_TOURS . " WHERE tour_name = '" . mysql_real_escape_string($show['Tour']) . "' AND tour_status = 'active'");
                    if (!$tour_exists) {
                        // Can't find a tour with this name, so we'll have to create it
                        $order = $wpdb->get_var("SELECT count(*) FROM " . GIGPRESS_TOURS . " WHERE tour_status = 'active'");
                        $order++;
                        $new_tour = array('tour_name' => gigpress_db_in($show['Tour']));
                        $wpdb->insert(GIGPRESS_TOURS, $new_tour);
                        $show['tour_id'] = $wpdb->insert_id;
                    } else {
                        $show['tour_id'] = $tour_exists;
                    }
                }
                // Check to see if we have this venue
                $venue_exists = $wpdb->get_var("SELECT venue_id FROM " . GIGPRESS_VENUES . " WHERE venue_name = '" . mysql_real_escape_string($show['Venue']) . "' AND venue_city = '" . mysql_real_escape_string($show['City']) . "' AND venue_country = '" . mysql_real_escape_string($show['Country']) . "'");
                if (!$venue_exists) {
                    // Can't find a venue with this name, so we'll have to create it
                    $new_venue = array('venue_name' => gigpress_db_in($show['Venue']), 'venue_address' => gigpress_db_in($show['Address']), 'venue_city' => gigpress_db_in($show['City']), 'venue_country' => gigpress_db_in($show['Country']), 'venue_url' => gigpress_db_in($show['Venue URL']), 'venue_phone' => gigpress_db_in($show['Venue phone']));
                    $wpdb->insert(GIGPRESS_VENUES, $new_venue);
                    $show['venue_id'] = $wpdb->insert_id;
                } else {
                    $show['venue_id'] = $venue_exists;
                }
                if ($show['Time'] == FALSE) {
                    $show['Time'] = '00:00:01';
                }
                if ($wpdb->get_var("SELECT count(*) FROM " . GIGPRESS_SHOWS . " WHERE show_artist_id = " . $show['artist_id'] . " AND show_date = '" . $show['Date'] . "' AND show_time = '" . $show['Time'] . "' AND show_venue_id = " . $show['venue_id'] . " AND show_status != 'deleted'") > 0) {
                    // It's a duplicate, so log it and move on
                    $duplicates[] = $show;
                } else {
                    if ($show['End date'] == FALSE) {
                        $show['show_multi'] = 0;
                        $show['End date'] = $show['Date'];
                    } else {
                        $show['show_multi'] = 1;
                    }
                    $new_show = array('show_date' => $show['Date'], 'show_time' => $show['Time'], 'show_multi' => $show['show_multi'], 'show_expire' => $show['End date'], 'show_artist_id' => $show['artist_id'], 'show_venue_id' => $show['venue_id'], 'show_tour_id' => $show['tour_id'], 'show_ages' => gigpress_db_in($show['Admittance']), 'show_price' => gigpress_db_in($show['Price']), 'show_tix_url' => gigpress_db_in($show['Ticket URL']), 'show_tix_phone' => gigpress_db_in($show['Ticket phone']), 'show_notes' => gigpress_db_in($show['Notes'], FALSE), 'show_related' => '0');
                    // Are we importing related post IDs?
                    if (isset($_POST['include_related']) && ($_POST['include_related'] = 'y')) {
                        $new_show['show_related'] = $show['Related ID'];
                    }
                    $formats = array('%s', '%s', '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%d');
                    $import = $wpdb->insert(GIGPRESS_SHOWS, $new_show, $formats);
                    if ($import != FALSE) {
                        $inserted[] = $show;
                    } else {
                        $skipped[] = $show;
                    }
                }
            }
            // end foreach import
            if (!empty($skipped)) {
                echo '<h4 class="error">' . count($skipped) . ' ' . __("shows were skipped due to errors", "gigpress") . '.</h4>';
                echo '<ul class="ul-square">';
                foreach ($skipped as $key => $show) {
                    echo '<li>' . wptexturize($show['Artist']) . ' ' . __("in", "gigpress") . ' ' . wptexturize($show['City']) . ' ' . __("at", "gigpress") . ' ' . wptexturize($show['Venue']) . ' ' . __("on", "gigpress") . ' ' . mysql2date($gpo['date_format'], $show['Date']) . '</li>';
                }
                echo '</ul>';
            }
            if (!empty($duplicates)) {
                echo '<h4 class="error">' . count($duplicates) . ' ' . __("shows were skipped as they were deemed duplicates", "gigpress") . '.</h4>';
                echo '<ul class="ul-square">';
                foreach ($duplicates as $key => $show) {
                    echo '<li>' . wptexturize($show['Artist']) . ' ' . __("in", "gigpress") . ' ' . wptexturize($show['City']) . ' ' . __("at", "gigpress") . ' ' . wptexturize($show['Venue']) . ' ' . __("on", "gigpress") . ' ' . mysql2date($gpo['date_format'], $show['Date']) . '</li>';
                }
                echo '</ul>';
            }
            if (!empty($inserted)) {
                echo '<h4 class="updated">' . count($inserted) . ' ' . __("shows were successfully imported", "gigpress") . '.</h4>';
                echo '<ul class="ul-square">';
                foreach ($inserted as $key => $show) {
                    echo '<li>' . wptexturize($show['Artist']) . ' ' . __("in", "gigpress") . ' ' . wptexturize($show['City']) . ' ' . __("at", "gigpress") . ' ' . wptexturize($show['Venue']) . ' ' . __("on", "gigpress") . ' ' . mysql2date($gpo['date_format'], $show['Date']) . '</li>';
                }
                echo '</ul>';
            }
        } else {
            // The file uploaded, but there were no results from the parse
            echo '<div id="message" class="error fade"><p>' . __("Sorry, but there was an error parsing your file. Maybe double-check your formatting and file type?", "gigpress") . '.</p></div>';
        }
        // Bye-bye
        unlink($upload['file']);
    } else {
        // The upload failed
        echo '<div id="message" class="error fade"><p>' . __("Sorry, but there was an error uploading", "gigpress") . ' <strong>' . $_FILES['gp_import']['name'] . '</strong>: ' . $upload['error'] . '.</p></div>';
    }
}
Beispiel #17
0
<pre>
<?php 
exit;
# include parseCSV class.
require_once '../parsecsv.lib.php';
# create new parseCSV object.
$csv = new parseCSV();
# Example conditions:
// $csv->conditions = 'title contains paperback OR title contains hardcover';
$csv->conditions = 'author does not contain dan brown';
// $csv->conditions = 'rating < 4 OR author is John Twelve Hawks';
// $csv->conditions = 'rating > 4 AND author is Dan Brown';
# Parse '_books.csv' using automatic delimiter detection.
$csv->auto('_books.csv');
# Output result.
// print_r($csv->data);
?>
</pre>
<style type="text/css" media="screen">
	table { background-color: #BBB; }
	th { background-color: #EEE; }
	td { background-color: #FFF; }
</style>
<table border="0" cellspacing="1" cellpadding="3">
	<tr>
		<?php 
foreach ($csv->titles as $value) {
    ?>
		<th><?php 
    echo $value;
    ?>
 /**
  * import_gradebook_screen( $vars )
  *
  * Hooks into screen_handler
  * Imports a CSV file data into the gradebook_screen(). It doesn't save anything!
  *
  * @param Array $vars a set of variables received for this screen template
  * @return Array $vars a set of variable passed to this screen template
  */
 function import_gradebook_screen($vars)
 {
     $is_nonce = nxt_verify_nonce($_POST['_nxtnonce'], 'gradebook_import_nonce');
     if (!$is_nonce) {
         $vars['die'] = __('BuddyPress Courseware Nonce Error while importing gradebook.', 'bpsp');
         return $this->gradebook_screen($vars);
     }
     $grades = array();
     if (isset($_FILES['csv_filename']) && !empty($_FILES['csv_filename'])) {
         require_once 'parseCSV.class.php';
         // Load CSV parser
         $csv = new parseCSV();
         $csv->auto($_FILES['csv_filename']['tmp_name']);
         foreach ($csv->data as $grade) {
             $id = bp_core_get_userid_from_nicename($grade['uid']);
             if ($id) {
                 $grades[$id] = $grade;
             }
         }
         if (count($csv->data) == count($grades)) {
             $vars['message'] = __('Data imported successfully, but it is not saved yet! Save this form changes to keep the data.', 'bpsp');
         } else {
             $vars['error'] = __('File data contains error or entries from other gradebook. Please check again.', 'bpsp');
         }
     }
     $vars['grades'] = $grades;
     $vars['assignment_permalink'] = $vars['assignment_permalink'] . '/gradebook';
     unset($_POST);
     return $this->gradebook_screen($vars);
 }
Beispiel #19
0
 /**
  * Create CSV File Export
  * @since 1.4
  * @version 1.0.1
  */
 public function download_export_log()
 {
     if (!isset($_REQUEST['mycred-export']) || $_REQUEST['mycred-export'] != 'do') {
         return;
     }
     // Must be logged in
     if (!is_user_logged_in()) {
         return;
     }
     // Make sure current user can export
     if (!apply_filters('mycred_user_can_export', false) && !$this->core->can_edit_creds()) {
         return;
     }
     // Security for front export
     if (apply_filters('mycred_allow_front_export', false) === true) {
         if (!isset($_REQUEST['token']) || !wp_verify_nonce($_REQUEST['token'], 'mycred-run-log-export')) {
             return;
         }
     } else {
         check_admin_referer('mycred-run-log-export', 'token');
     }
     $type = '';
     $data = array();
     // Sanitize the log query
     foreach ((array) $_POST as $key => $value) {
         if ($key == 'action') {
             continue;
         }
         $_value = sanitize_text_field($value);
         if ($_value != '') {
             $data[$key] = $_value;
         }
     }
     // Get exports
     $exports = mycred_get_log_exports();
     if (empty($exports)) {
         return;
     }
     // Identify the export type by the action button
     foreach ($exports as $id => $info) {
         if ($info['label'] == $_POST['action']) {
             $type = $id;
             break;
         }
     }
     // Act according to type
     switch ($type) {
         case 'all':
             $old_data = $data;
             unset($data);
             $data = array();
             $data['ctype'] = $old_data['ctype'];
             $data['number'] = -1;
             break;
         case 'search':
             $data['number'] = -1;
             break;
         case 'displayed':
         default:
             $data = apply_filters('mycred_export_log_args', $data);
             break;
     }
     // Custom Exports
     if (has_action('mycred_export_' . $type)) {
         do_action('mycred_export_' . $type, $data);
     } else {
         // Query the log
         $log = new myCRED_Query_Log($data, true);
         // If there are entries
         if ($log->have_entries()) {
             $export = array();
             // Loop though results
             foreach ($log->results as $entry) {
                 // Remove the row id
                 unset($entry['id']);
                 // Make sure entry and data does not contain any commas that could brake this
                 $entry['entry'] = str_replace(',', '', $entry['entry']);
                 $entry['data'] = str_replace(',', '.', $entry['data']);
                 // Add to export array
                 $export[] = $entry;
             }
             $log->reset_query();
             // Load parseCSV
             require_once myCRED_ASSETS_DIR . 'libs/parsecsv.lib.php';
             $csv = new parseCSV();
             // Run output and lets create a CSV file
             $date = date_i18n('Y-m-d');
             $csv->output(true, 'mycred-log-' . $date . '.csv', $export, array('ref', 'ref_id', 'user_id', 'creds', 'ctype', 'time', 'entry', 'data'));
             die;
         }
         $log->reset_query();
     }
 }
Beispiel #20
0
 private function mapFileInvoice()
 {
     $file = Input::file('file');
     if ($file == null) {
         Session::flash('error', trans('texts.select_file'));
         return Redirect::to('company/import_export');
     }
     $name = $file->getRealPath();
     require_once app_path() . '/includes/parsecsv.lib.php';
     $csv = new parseCSV();
     $csv->heading = false;
     $csv->auto($name);
     Session::put('data', $csv->data);
     $headers = false;
     $hasHeaders = false;
     $mapped = array();
     $columns = array('', Invoice::$fieldCodClient, Invoice::$fieldProduct, Invoice::$fieldAmount);
     if (count($csv->data) > 0) {
         $headers = $csv->data[0];
         foreach ($headers as $title) {
             if (strpos(strtolower($title), 'name') > 0) {
                 $hasHeaders = true;
                 break;
             }
         }
         for ($i = 0; $i < count($headers); $i++) {
             $title = strtolower($headers[$i]);
             $mapped[$i] = '';
             if ($hasHeaders) {
                 $map = array('cod_client' => Invoice::$fieldCodClient, 'product' => Invoice::$fieldProduct, 'amount' => Invoice::$fieldAmount);
                 foreach ($map as $search => $column) {
                     foreach (explode("|", $search) as $string) {
                         if (strpos($title, 'sec') === 0) {
                             continue;
                         }
                         if (strpos($title, $string) !== false) {
                             $mapped[$i] = $column;
                             break 2;
                         }
                     }
                 }
             }
         }
     }
     $data = array('data' => $csv->data, 'headers' => $headers, 'hasHeaders' => $hasHeaders, 'columns' => $columns, 'mapped' => $mapped);
     $data['branches'] = Branch::where('account_id', '=', Auth::user()->account_id)->orderBy('id')->get();
     return View::make('accounts.import_map_invoice', $data);
 }
Beispiel #21
0
    }
    return $hashMap;
}
function hkey($title)
{
    return strtolower($title);
}
if (isset($_POST["source"])) {
    $source = $_POST["source"];
}
$fileName = upload($source);
echo $fileName . "<br/>";
echo $source . "<br/>";
if ($fileName != null) {
    $db = new MongoHQ(array('collectionName' => 'watched'));
    $csv = new parseCSV($fileName);
    $csv->auto();
    $data = $csv->data;
    //print_r($data);
    if ($source == "imdb") {
        $movies = IMDB::buildMovies($data);
        var_dump(Movie::toMoviesDB($movies));
        $db->saveMany(Movie::toMoviesDB($movies));
    } else {
        if ($source == "google") {
            $hashMap = buildHash($data);
            $db_movies = $db->find();
            $mismatched = array();
            foreach (Movie::toMovies($db_movies) as $movie) {
                $title = $movie->TITLE;
                //echo "<br/><div>[" . $$movie->POSITION . "] processing movie title: " . $title . " [db/rotten]</div>";
Beispiel #22
0
function csvFileread($target_file)
{
    # include parseCSV class.
    require_once 'parsecsv.lib.php';
    $conn = mysql_connect("localhost", "root", "proggasoft123") or die("unable to connect localhost" . mysql_error());
    $db = mysql_select_db("testfile", $conn) or die("unable to select db name");
    # create new parseCSV object.
    $csv = new parseCSV();
    # Parse '_books.csv' using automatic delimiter detection...
    $csv->auto("uploads/{$target_file}.csv");
    //$csv->auto("abc.csv");
    # ...or if you know the delimiter, set the delimiter character
    # if its not the default comma...
    $csv->delimiter = "\t";
    # tab delimited
    # ...and then use the parse() function.
    // $csv->parse('_books.csv');
    # Output result.
    // print_r($csv->data);
    $i = 0;
    foreach ($csv->data as $key => $row) {
        //print_r($row);
        //if ($i == 5)
        //die();
        //Work on Main category...........
        $main_category = mysql_real_escape_string($row['Categories']);
        $maincatesql = "INSERT INTO main_catagories (main_catagory) values ('" . $main_category . "')";
        //echo $catesql;
        $result = mysql_query($maincatesql);
        if ($result) {
            //$main_cat_id = "query of last id";
            $main_cat_id = mysql_insert_id();
        } else {
            die('not successfuly');
        }
        //Work on Category...........
        $category = mysql_real_escape_string($row['Mypafway Categories']);
        $catesql = "INSERT INTO categories (main_cat_id,title) values ('" . $main_cat_id . "','" . $category . "')";
        $result = mysql_query($catesql);
        if ($result) {
            //$cat_id = "query of last id";
            $cat_id = mysql_insert_id();
        } else {
            die('not successfuly');
        }
        //Work on Subcategory...........
        $subcategory = mysql_real_escape_string($row['Mypafway Sub Categories']);
        $subcatesql = "INSERT INTO sub_categories (main_cat_id,cat_id,title) values ('" . $main_cat_id . "','" . $cat_id . "','" . $subcategory . "')";
        $subcatresult = mysql_query($subcatesql);
        if ($subcatresult) {
            //$cat_id = "query of last id";
            $subcat_id = mysql_insert_id();
        } else {
            die('not successfuly');
        }
        //Work on Make table...........
        $make = mysql_real_escape_string($row['Make']);
        $makesql = "INSERT INTO  auto_makes (text) values ('" . $make . "')";
        $makeresult = mysql_query($makesql);
        if ($makeresult) {
            //$cat_id = "query of last id";
            $make_id = mysql_insert_id();
        } else {
            die('not successfuly make');
        }
        //Work on Model table...........
        $model = mysql_real_escape_string($row['Model']);
        $modelsql = "INSERT INTO  auto_models (auto_make_id,text,year,Cylinders,Engine_Code,Engine_Bore,Engine_Size,Comments_on_file) \n        values ('" . $make_id . "','" . $model . "','','','','','','')";
        $modelresult = mysql_query($modelsql);
        if ($modelresult) {
            //$cat_id = "query of last id";
            $model_id = mysql_insert_id();
        } else {
            die('not successfuly model');
        }
        //Work on Product...........
        $product_name = mysql_real_escape_string($row['Name']);
        //echo $product_make = $row['Make'];
        //echo $product_model = $row['Model'];
        $product_yaer = mysql_real_escape_string($row['Year']);
        $product_price = mysql_real_escape_string($row['Price']);
        $product_image = mysql_real_escape_string($row['Images']);
        //echo $product_desc = $row['Short Description'];
        $product_desc = mysql_real_escape_string($row['Long Description']);
        $product_metatitle = mysql_real_escape_string($row['Meta Title']);
        $product_metadesc = mysql_real_escape_string($row['Meta Description']);
        $product_tags = mysql_real_escape_string($row['Tags']);
        // echo $product ="INSERT INTO products (name,company,description,price,categories,subcategories,picture,year,make,model)
        // values ('".$product_name."', 'mypafway', '".$product_desc."','".$product_price."','".$cat_id."','".$subcat_id."','".$product_image."','".$product_yaer."','".$product_make."','".$product_model."')";
        $product = "INSERT INTO products (user_id,title,partno,company,url,description,price,\n        product_type,Quantity,headings,categories,subcategories,show_address,show_phone,show_cell,show_fax,\n        picture,year,make,model,location,time,supp1,supp2,supp3,supp4,supp5,search_count,pushed,downloads,\n        meta_title,meta_description,tags)\n        \n      values ('','" . $product_name . "','','','','{$product_desc}','" . $product_price . "','','','','" . $cat_id . "','" . $subcat_id . "',\n            'a','a','a','a','" . $product_image . "','" . $product_yaer . "','" . $make_id . "',\n             '" . $model_id . "','','','','','','','','','','','" . $product_metatitle . "','" . $product_metadesc . "','" . $product_tags . "')";
        $productresult = mysql_query($product);
        if ($productresult) {
            //$cat_id = "query of last id";
            $subcat_id = mysql_insert_id();
        } else {
            die('not successfuly product');
        }
        //Work on Search keyword table...........
        $searchkey = $row['Meta Keywords'];
        $searchkeysql = "INSERT INTO  search (date,keyword) values ('','" . $searchkey . "')";
        $result = mysql_query($searchkeysql);
        if ($result) {
            //$cat_id = "query of last id";
            $cat_id = mysql_insert_id();
            //echo "CSV file upload successfuly.";
        } else {
            die('not successfuly');
        }
        //$i++;
    }
}
<?php

require_once '/lib/csv/parsecsv.lib.php';
require_once '/config.php';
$file = "one";
#file name of csv
# create new parseCSV object.
$csv = new parseCSV();
#Parse '_books.csv' using automatic delimiter detection...
$csv->auto('./uploads/' . $file . '.csv');
//print_r($csv->data);
$parent = basename(dirname($_SERVER['PHP_SELF']));
$mysql = mysqli_connect(DBHOST, DBUSER, DBPASSWORD);
mysqli_select_db($mysql, DBNAME);
$result = mysqli_query($mysql, "Truncate table mailinglist");
$result = mysqli_query($mysql, "\n\t LOAD DATA  INFILE '" . UPLOADS . $file . ".csv' INTO TABLE mailinglist FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (email)\n\t");
// LOAD DATA  INFILE 'C://xampp//htdocs//DEMLa//uploads//one.csv' INTO TABLE mailinglist FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (email)
header('Content-Type: application/json');
if (!$result) {
    $error = mysqli_error($mysql);
    $data2 = array('dbload' => 'failed', 'error' => $error);
    echo json_encode($data2);
} else {
    $result = mysqli_query($mysql, "SELECT * FROM mailinglist");
    // Return the number of rows in result set
    $rowcount = mysqli_num_rows($result);
    $data2 = array('dbload' => 'success', 'indb' => $rowcount, 'incsv' => count($csv->data) + 1);
    echo json_encode($data2);
}
mysqli_close($mysql);
<?php

header('Content-Type: application/json');
require_once '../parsecsv-for-php/parsecsv.lib.php';
$csv = new parseCSV();
$csv->parse('../../../00_ADMIN_CSV_FOLDER/extra_pricing_minutes.csv');
echo json_encode($csv->data);
 /**
  * Function to generate a CSV file from submitted form values. This function is called by Tx_Formhandler_Controller_Backend
  *
  * @param array $records The records to export to CSV
  * @param array $exportParams A list of fields to export. If not set all fields are exported
  * @see Tx_Formhandler_Controller_Backend::generateCSV()
  * @return void
  */
 public function generateModuleCSV($records, $exportParams = array(), $delimiter = ',', $enclosure = '"', $encoding = 'utf-8', $fileName = 'formhandler.csv')
 {
     $data = array();
     $dataSorted = array();
     //build data array
     foreach ($records as $idx => $record) {
         if (!is_array($record['params'])) {
             $record['params'] = array();
         }
         foreach ($record['params'] as $subIdx => &$param) {
             if (is_array($param)) {
                 $param = implode(';', $param);
             }
         }
         if (count($exportParams) == 0 || in_array('pid', $exportParams)) {
             $record['params']['pid'] = $record['pid'];
         }
         if (count($exportParams) == 0 || in_array('submission_date', $exportParams)) {
             $record['params']['submission_date'] = date('d.m.Y H:i:s', $record['crdate']);
         }
         if (count($exportParams) == 0 || in_array('ip', $exportParams)) {
             $record['params']['ip'] = $record['ip'];
         }
         $data[] = $record['params'];
     }
     if (count($exportParams) > 0) {
         foreach ($data as $idx => &$params) {
             // fill missing fields with empty value
             foreach ($exportParams as $key => $exportParam) {
                 if (!array_key_exists($exportParam, $params)) {
                     $params[$exportParam] = '';
                 }
             }
             // remove unwanted fields
             foreach ($params as $key => $value) {
                 if (!in_array($key, $exportParams)) {
                     unset($params[$key]);
                 }
             }
         }
     }
     // sort data
     $dataSorted = array();
     foreach ($data as $idx => $array) {
         $dataSorted[] = $this->sortArrayByArray($array, $exportParams);
     }
     $data = $dataSorted;
     // create new parseCSV object.
     $csv = new parseCSV();
     $csv->delimiter = $csv->output_delimiter = $delimiter;
     $csv->enclosure = $enclosure;
     $csv->input_encoding = strtolower($this->getInputCharset());
     $csv->output_encoding = strtolower($encoding);
     $csv->convert_encoding = FALSE;
     if ($csv->input_encoding !== $csv->output_encoding) {
         $csv->convert_encoding = TRUE;
     }
     $csv->output($fileName, $data, $exportParams);
     die;
 }
 function download()
 {
     App::import("Vendor", "parsecsv");
     $csv = new parseCSV();
     $filepath = "C:\\Users\\Administrator\\Downloads" . "german_listings.csv";
     $csv->auto($filepath);
     $this->set('german_listings', $this->GermanListing->find('all'));
     $this->layout = null;
     $this->autoLayout = false;
     Configure::write('debug', '0');
 }
 /**
  * Load Export
  * Creates a CSV export file of the 'mycred-export-raw' transient.
  * @since 1.3
  * @version 1.1
  */
 public function load_export()
 {
     // Security
     if ($this->core->can_edit_plugin()) {
         $export = get_transient('mycred-export-raw');
         if ($export === false) {
             return;
         }
         if (isset($export[0]['mycred_log'])) {
             $headers = array('mycred_user', 'mycred_amount', 'mycred_ctype', 'mycred_log');
         } else {
             $headers = array('mycred_user', 'mycred_amount', 'mycred_ctype');
         }
         require_once myCRED_ASSETS_DIR . 'libs/parsecsv.lib.php';
         $csv = new parseCSV();
         delete_transient('mycred-export-raw');
         $csv->output(true, 'mycred-balance-export.csv', $export, $headers);
         die;
     }
 }
 /**
  * Converts data array into CSV outputs it to the browser
  */
 public function ajax_export_csv()
 {
     // Purposely using $_REQUEST here since this method can work via a GET and POST request
     // POST requests are used when passing the data value since it's too big to pass via GET
     if (!is_numeric($_REQUEST['post_id']) || !current_user_can('edit_post', absint($_REQUEST['post_id']))) {
         wp_die('Unauthorized access', 'You do not have permission to do that', array('response' => 401));
     }
     $post = get_post(absint($_REQUEST['post_id']));
     // If the user passed a data value in their request we'll use it after validation
     if (isset($_POST['data']) && isset($_POST['title'])) {
         $data = m_chart()->validate_data(json_decode(stripslashes($_POST['data'])));
         $file_name = sanitize_title($_POST['title']);
     } else {
         $data = m_chart()->get_post_meta($post->ID, 'data');
         $file_name = sanitize_title(get_the_title($post->ID));
     }
     if (empty($data)) {
         return;
     }
     require_once __DIR__ . '/external/parsecsv/parsecsv.lib.php';
     $parse_csv = new parseCSV();
     $parse_csv->output($file_name . '.csv', $data);
     die;
 }
<?php

# include parseCSV class.
require_once '../parsecsv.lib.php';
# create new parseCSV object.
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...
$csv->auto('_books.csv');
# ...or if you know the delimiter, set the delimiter character
# if its not the default comma...
// $csv->delimiter = "\t";   # tab delimited
# ...and then use the parse() function.
// $csv->parse('_books.csv');
# now we have data in $csv->data, at which point we can modify
# it to our hearts content, like removing the last item...
array_pop($csv->data);
# then we output the file to the browser as a downloadable file...
$csv->output('books.csv');
# ...when the first parameter is given and is not null, the
# output method will itself send the correct headers and the
# data to download the output as a CSV file. if it's not set
# or is set to null, output will only return the generated CSV
# output data, and will not output to the browser itself.
 public function mapFile($entityType, $filename, $columns, $map)
 {
     require_once app_path() . '/Includes/parsecsv.lib.php';
     $csv = new parseCSV();
     $csv->heading = false;
     $csv->auto($filename);
     Session::put("{$entityType}-data", $csv->data);
     $headers = false;
     $hasHeaders = false;
     $mapped = array();
     if (count($csv->data) > 0) {
         $headers = $csv->data[0];
         foreach ($headers as $title) {
             if (strpos(strtolower($title), 'name') > 0) {
                 $hasHeaders = true;
                 break;
             }
         }
         for ($i = 0; $i < count($headers); $i++) {
             $title = strtolower($headers[$i]);
             $mapped[$i] = '';
             if ($hasHeaders) {
                 foreach ($map as $search => $column) {
                     if ($this->checkForMatch($title, $search)) {
                         $mapped[$i] = $column;
                         break;
                     }
                 }
             }
         }
     }
     $data = array('entityType' => $entityType, 'data' => $csv->data, 'headers' => $headers, 'hasHeaders' => $hasHeaders, 'columns' => $columns, 'mapped' => $mapped);
     return $data;
 }