How can I export data tab separated - laravel

I'm exporting some Data from a DB and I want to have the 2 columns that I generate Tab separated.
I've already tried to use implode after my fputcsv but it always appears comma separated. Also tried changing my separator (,) to some other character, but a comma is always printed in the CSV.
This is the function that I'm using for it.
public function ResearchExport(Request $request)
{
//Export ProductID and KitID of all the Kits created from the given date to the actual moment
$TubeAddDate = $request->input('TubeAddDate');
$select = DB::table('tubes')->select('TubeBarcodeID', 'ActivationCode')->where('LOG_important', '2')->whereBetween('TubeAddDate', array($TubeAddDate, NOW()))->get();
$tot_record_found=0;
if (count($select)>0) {
$tot_record_found=1;
$CsvData=array('TubeBarcodeID,ActivationCode');
foreach ($select as $value) {
$CsvData[]=$value->TubeBarcodeID.",".$value->ActivationCode.;
}
$filename=date('Y-m-d').".csv"; //stores the file with the date of today as name
$file_path=storage_path().'/'.$filename;
$file = fopen($file_path, "w+");
foreach ($CsvData as $exp_data) {
fputcsv($file, explode(",", $exp_data));
}
fclose($file);
return response()->download($file_path, $filename);
}
return view('InsertForms/download', ['record_found' =>$tot_record_found]);
}
At the moment I'm getting this as output
TubeBarcodeID,ActivationCode
FF01111112,IKG5G-B0FIZ
FF0111113,6XMP8-760Y3
but I expect something tab separated in the CSV like this
TubeBarcodeID ActivationCode
FF01111112 IKG5G-B0FIZ
FF0111113 6XMP8-760Y3

So I actually just solved thanks to one of the commentaries that pointed out my error.
I just had to change my .csv to .xls and then override the third parameter of fputcsv with a "\t".
$filename=date('Y-m-d').".xls"; //stores the file with the date of today as name
$file_path=storage_path().'/'.$filename;
$file = fopen($file_path, "w+");
foreach ($CsvData as $exp_data) {
fputcsv($file, explode(",", $exp_data), "\t");
}

Related

laravel Backpack Original Image Name

I am using laravel backpack for my site and i need to upload some images, i copy the code from their website and works fine, but i need the original name on the images, i tried some things, but is not working.
public function setImageAttribute($value)
{
$attribute_name = "image";
$disk = "uploads";
$destination_path = 'storage/services/' .date('FY').DIRECTORY_SEPARATOR;
if ($value==null) {
Storage::disk($disk)->delete($this->{$attribute_name});
// set null in the database column
$this->attributes[$attribute_name] = null;
}
if (str_starts_with($value, 'data:image'))
{
$file = $value;
$filename = $this->generateFileName($file, $destination_path);
$image = InterventionImage::make($file)->orientate();
$fullPath = $destination_path.$filename.'.'.$file->getClientOriginalExtension();
$this->attributes[$attribute_name] = $fullPath;
}
protected function generateFileName($file, $destination_path)
{
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension());
$filename = Str::random(20);
while (Storage::disk('uploads')->exists($destination_path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = Str::random(20);
}
return $filename;
}
why value alwys take image base64
is there any way to git image original name?
As far as I know, you won't be able to retrieve the filename, as it's always a base64 file. But maybe this work around helps you:
Image fields blade file can be found at:
\vendor\backpack\crud\src\resources\views\crud\fields\image.blade.php
You can overwrite it by making a file on the same name at:
\resources\views\vendor\backpack\crud\fields\image.blade.php
You can change anything there, maybe you can add a hidden input with the file name.

export csv file from mysql database in laravel 5

I have done import in laravel 5 but facing some problem while exporting file.
code is not proper and doesnot give any logic.
I have tried similiar to documentation
public function exportData(Test $test,Excel $excel){
$test=$test->all();
Excel::create('Test excel', function($test) {
$test->sheet('sheet1', function($sheet) {
$sheet->setOrientation('landscape');
});
})->export('xls');
}
how to export csv file from mysql?
I am using "maatwebsite/excel": "~2.0.0" package
You can use INTO OUTFILE in Laravel
public function exportData($file_name) {
$file = public_path()."/downloads/".$file_name; //CSV file is store this path
$query = sprintf("select * from tests INTO OUTFILE '%s' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n'",$file);
\DB::connection()->getpdo()->exec($query);
}
You might consider using the league/csv package. They have an example of exporting a database query to CSV. In your case, it would look something like:
public function exportData() {
// get the data
$data = Test::all();
// get a Writer object for writing to CSV
$csv = League\Csv\Writer::createFromFileObject(new SplTempFileObject());
// add the data to the writer
$csv->insertAll($data);
// output the file
$csv->output('testdata.csv');
}

Change the maximum amount of characters in the Meta Description

I have a problem to change the limit of characters in the meta description. I\\’ve modified as shown here:
http://www.magentocommerce.com/boards/v/viewthread/278911/#t392935
But it only detects if you create or modify the product from magento admin and I upload products from .csv file and I have to go one by one to each product in the meta description and then go down from 255 to 155: (
Is there any way to change it without changing it from Magento, I think the problem comes because the code says:
setOnkeyup
Thanks in advance and greetings!
I understand, that you have too long data in your meta_description for each of products.
You can short the value before loading it by layout XML config, or directly by the PHTML template for each page type.
Better way to have result you need is NOT ti import longest data than you need.
Importing unnecessary data solving import and after that you need to correct it again.
Maybe will be better to make script to cut-out meta description in CSV file before you start import to magento.
I solved simmilar issue and make something like this:
(script take your csv file and make new with only 2 columns, SKU and updated text named DECSRIPTION, than you can import to magento after your firs import of csv (first import everything without meta description, after that ONLY your meta description cuted out by 250 chars for example))
//////// get csv and take variable you need in my case is it SKU
$csv = file_get_contents ('myimportfile.csv');
function parse_csv ($csv_string, $delimiter = ";", $skip_empty_lines = true, $trim_fields = true)
{
$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
$enc = preg_replace_callback(
'/"(.*?)"/s',
function ($field) {
return urlencode(utf8_encode($field[1]));
},
$enc
);
$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
return array_map(
function ($line) use ($delimiter, $trim_fields) {
$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
return array_map(
function ($field) {
return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
},
$fields
);
},
$lines
);
}
// list of variables to array
$vystup = parse_csv($csv);
enter code here
After that you can loop each variable to row, modify by PHP what you want:
$seznamsku = array();
foreach ($vystup as $row){
array_push($seznamsku, $sku[0]);
unset($seznamsku[0]);
$seznamskufin = array_filter($seznamsku, 'strlen');
};
foreach ($seznamskufin as $row) {
$__OUT .= ' "ROW_YOURSKU","'.htmlspecialchars(substr(ROW_YOURMETADESCRIPTION, 0, 155)).'"'."\n"; // TODO exactly dont know how to call variables, maybye $row['something'] or $row[0]['something']
};
$feed = fopen($newfile, 'w');
fwrite($feed, $__OUT);
fclose($feed);
//remember to unset variables
you can get another csv file with description long 250 chars and import it to magento
(You must update code it only returns list of SKU, get your descriptions from file);

How to return variable values in codeigniter language line strings?

To be more clear, none of these lines in default language's general_lang.php work:
$lang['general_welcome_message'] = 'Welcome, %s ( %s )';
or
$lang['general_welcome_message'] = 'Welcome, %1 ( %2 )';
I expect an output like Welcome, FirstName ( user_name ).
I followed the second (not accepted) answer at https://stackoverflow.com/a/10973668/315550.
The code I write in the view is:
<div id="welcome-box">
<?php echo lang('general_welcome_message',
$this->session->userdata('user_firstname'),
$this->session->userdata('username')
);
?>
</div>
I use codeigniter 2.
You will need to use php's sprintf function (http://php.net/manual/en/function.sprintf.php)
Example from http://ellislab.com/forums/viewthread/145634/#749634:
//in english
$lang['unread_messages'] = "You have %1$s unread messages, %2$s";
//in another language
$lang['unread_messages'] = "Hi %2$s, You have %1$s unread messages";
$message = sprintf($this->lang->line(‘unread_messages’), $number, $name);
I extended Code CI_Lang class like this..
class MY_Lang extends CI_Lang {
function line($line = '', $swap = null) {
$loaded_line = parent::line($line);
// If swap if not given, just return the line from the language file (default codeigniter functionality.)
if(!$swap) return $loaded_line;
// If an array is given
if (is_array($swap)) {
// Explode on '%s'
$exploded_line = explode('%s', $loaded_line);
// Loop through each exploded line
foreach ($exploded_line as $key => $value) {
// Check if the $swap is set
if(isset($swap[$key])) {
// Append the swap variables
$exploded_line[$key] .= $swap[$key];
}
}
// Return the implode of $exploded_line with appended swap variables
return implode('', $exploded_line);
}
// A string is given, just do a simple str_replace on the loaded line
else {
return str_replace('%s', $swap, $loaded_line);
}
}
}
ie. In your language file:
$lang['foo'] = 'Thanks, %s. Your %s has been changed.'
And where-ever you want to use it (controller / view etc.)
echo $this->lang->line('foo', array('Charlie', 'password'));
Will produce
Thanks, Charlie. Your password has been changed.
This handles single 'swaps' as well as multiple
Also it won't break any existing calls to $this->lang->line.

Generate MS word document in Joomla

What I try to accomplish:
Admin creates MS Word document with placeholders that will be filled with data from Joomla database
Admin uploades MS Word file to Joomla and connects it with SQL statement
User execute "Generate MS Word" function and gets MS Word document filled with data from database.
Is there any components for Joomla that does this?
I have done this in my application using Interop libraries.
recently I've done this for a joomla component using phpdocx and pclzip libraries, where
a *.docx file is generated from a template file.
Config:
$params = Object with form data; // data from requeest
$template = 'xml_file_name'; // jfrom xml file name and *.docx template file name
$pl = '#'; // place holder prefix & suffix: (example: #PLACEHOLDER#)
$date_placehold = '#DATE#'; // will be replaced with current date
$date_formt = 'F j, Y'; // php date format
$template_path = JPATH_COMPONENT_SITE .DS.'templates'.DS.$template.'.docx';
$temp_dir = JPATH_ROOT.DS.'tmp'.DS.'phpdocx-temp-dir'; // + write access
$output_mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
$filename = $params->first_name .' - '. $params->second_name.'.docx';
// get names of all form fields of type 'list' from xml file
$lists = (array) ComponentHelper::getJFormLists($template);
// get all field names from the xml file
$fields = (array) ComponentHelper::getJFormFieldsNames($template);
Initialize variables:
$doc =& JFactory::getDocument();
$doc->setMimeEncoding($output_mime);
// require phpdocx class
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'pclzip.lib.php');
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers'.DS.'phpdocx.php');
$phpdocx = new phpdocx($template_path, $temp_dir);
bind form fields with user params:
foreach($params as $field => $value)
{
if(array_key_exists($field,$lists) && is_array($lists[$field]) && array_key_exists($value, $lists[$field]) )
{
// if the field is JFormInput with type "list" its value is not important but its label
$var = $lists[$field][$value];
} else {
$var = $value;
}
// use openxml carriage return on new lines
if(strpos($var, "\n")) {
$var = str_replace("\n", '<w:br/>', $var);
}
$fields[$field] = $var;
}
foreach application form fields:
foreach($fields as $field => $value)
{
// replace placeholder with form value
$phpdocx->assign($pl.strtoupper($field).$pl, $value);
}
// assign date for filled-in applications
if(!empty($date_placehold)
{
$phpdocx->assign($date_placehold, date($date_formt));
}
output the file:
$phpdocx->stream($filename, $output_mime);
return true;

Resources