I exported the reviews from my magento website in csv format. Reviews contains :,;,?,! etc. Normally reviews are well in fields. When the review contain ; ,it's get splitted to next field. (I opened the csv file using OpenOffice spreadsheet)
For Example:
Review -> It's nice to use; looks good.
Now output ->
Field A-> It's nice to use
Field B-> looks good
Expected Output
Field A ->It's nice to use; looks good
I used the following header to export as acsv file in php
header('Content-type: application/utf-8');
header('Content-disposition: attachment; filename="file.csv"');
How can I get my expected output?
I would advise tackling the problem from the other side - I believe this is a bone of contention for Magento as some users want the semi-colon.
I would suggest looking at the way you use openoffice - It has been a while but I believe there is an option during the load of the csv called "Separator options" - Change these and all should work well.
The sad thing is if this is the correct answer it is off topic :-( but I hope this helps you achieve your goal!
Thanks,
//P
I'm using this class I've made for exporting data as a CSV spreadsheet. The trick is fputcsv() which should do the formatting right. Then, of course, you must properly import it to OpenOffice (or LibreOffice now), but that's different story.
Maybe it'll help you out.
<?php
class Spreadsheet {
private $grid = array();
/**
* Set cell value at position X, Y
*/
public function setCell($x, $y, $value) {
for($yy=0; $yy<=$y; $yy++) {
if(!isset($this->grid[$yy])) {
$this->grid[$yy] = array();
}
}
for($xx=0; $xx<=$x; $xx++) {
if(!isset($this->grid[$y][$xx])) {
$this->grid[$y][$xx] = null;
}
}
$this->grid[$y][$x] = $value;
}
/**
* final command executed, including "exit".
* Sends CSV to browser.
*/
public function sendAsCsv(/*string*/ $filename) {
header('Content-type: text/csv; charset=utf-8');
header('Content-Language: cs');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header("Pragma: no-cache");
header("Expires: 0");
ob_end_clean();
$outputBuffer = fopen("php://output", 'w');
$this->appendToFile($outputBuffer);
fclose($outputBuffer);
exit;
}
/**
* Appends content to a file (rarely used outside this class)
*/
public function appendToFile(/*resource*/ $fileHandle) {
foreach($this->grid as $val) {
fputcsv($fileHandle, $val);
}
}
}
Related
Data in csv file is not in proper format it show like as javascript code or html code in only one column
Code in userscontroller
for export data in csvfile from database of user table
public function export() {
$this->response->download("export.csv");
$data = $this->Users->find('all');
$this->set(compact('data'));
$this->layout = 'ajax';
return;
}
// app/Views/Users/export
header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=export.csv");
foreach ($data as $row) {
foreach ($row['Users'] as $cell) {
// Escape double quotation marks
$cell = '"' . preg_replace('/"/','""',$cell) . '"';
}
echo implode(',', $row['Users']) . "\n";
}
Screenshot of output:
As I see here, Look like it is debug variable for debug bar or something like that (cause i not have full view of your csv file)
So I can suggest some action to check as i know:
Check "your template" file as see $this->layout = 'ajax'; . It may contain default debug bar or custom code. Empty ajax layout look like this
Because CSV file is not normal view. So better you just set this action not use any view layout by using $this->layout = false; or in Cake 3 use $this->viewBuilder()->layout(false);
Sometime php code also inject to output file or view page because your code have notice or warning message. So please check the full csv file, start read from where html code begin and you will understand the problem
I have a problem with calling PHPWord library in Code Igniter, I already using PHPExcel and there are no problems everything goes smoothly.
But I have a problem with this PHPWord, because when I tried to use the same method to call the PHPExcel, it doesnt solve anything. I still seeing an error.
It's not like I don't search it on the google, I already searched it, but still, no one can solve my problem, I don't where is the problem.
So let me explain what is the problem.
FYI: I using PHP 7.1.1
Because the PHP version, PHPWord got some errors that says a class named as a String that is known as variable, so because of that error, I changed it to Strings all of them that associated with that class.
After I changed it, I want to call the class with library file.
This is the file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH.'/third_party/PHPWord/Autoloader.php';
use PhpOffice\PhpWord\Autoloader as Autoloader;
use PhpOffice\PhpWord\Settings as Settings;
use PhpOffice\PhpWord\PhpWord as PhpWord;
/* I tried two different ways */
// class Word extends PhpWord {
// public function __construct() {
// parent::__construct();
// }
// }
Autoloader::register();
Settings::loadConfig();
And this is the Controller code that calls the class.
$this->load->library('word');
$section = $this->word->createSection(array('orientation'=>'landscape'));
After I did that, it says Non-existent class: Word, I don't know anymore where is the problem, is it because I changed the class name? or it doesn't compatible with my CI version(3)?
Because I already tried different ways and still cannot solve this problem, can someone help me with this problem and show me what I did wrong? Thank you.
I haven't tried with PHP7 but I found this Github repo which worked for me.
https://github.com/webeasystep/phpword_codeigniter
I just copied the application\third_party\PhpWord folder and application\library\PhpWord.php into the same locations in my project and then used some of the code from the controller provided, e.g...
public function test()
{
$this->load->library('Phpword');
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$phpWord->getCompatibility()->setOoxmlVersion(14);
$phpWord->getCompatibility()->setOoxmlVersion(15);
$filename = 'test.docx';
// add style settings for the title and paragraph
$section = $phpWord->addSection();
$section->addText("Hello, world");
$section->addTextBreak(1);
$section->addText("It's cold outside.");
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($filename);
// send results to browser to download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename); // deletes the temporary file
exit;
}
This works fine, I get a .docx when I hit my controller/test in a browser
Following library is working smoothly for me for PHP 7 version without any error.
https://github.com/rifqisucahyo/CI_PHPWord
class Word extends PHPWord {
public function __construct() {
parent::__construct();
$this->load->library('word');
}
function index() {
require_once APPPATH."/third_party/PHPWord.php";
$PHPWord = $this->word; // New Word Document
$section = $PHPWord->createSection(); // New portrait section
// Add text elements
$section->addText('Hello World!');
$section->addTextBreak(2);
$section->addText('Mohammad Rifqi Sucahyo.', array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);
$PHPWord->addFontStyle('rStyle', array('bold'=>true, 'italic'=>true, 'size'=>16));
$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
// Save File / Download (Download dialog, prompt user to save or simply open it)
$section->addText('Ini Adalah Demo PHPWord untuk CI', 'rStyle', 'pStyle');
$filename='just_some_random_name.docx'; //save our document as this file name
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('php://output');
}
}
I have a function that creates an HTML page and forces the download. Once the function is run, for some reason it is downloaded to the users computers twice. Here is my code
public function actionDownload($params)
{
// Get the article
$co_model=new Contentorder;
$co_model->load($params['id']);
$co=$co_model->getFields();
$file_name=str_replace(array(' ','.','&',',','\''),'',strtolower($co['article_title'])).".html";
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-type: text/html');
echo '<!DOCTYPE html><head><title>'.$co['article_title'].'</title></head><body>';
if ($co['id_contenttype']==3){ // Reusable
$lco_model=new Librarycontent;
$lco_model->load($co['id_librarycontent']);
$res=$lco_model->getFields();
if ($res['id_reusabletype']==3) // Youtube
{
echo $res['reusable_file'];
}
}
echo $co['article'].'</body></html>';
exit;
}
It successfully forces the download on the dynamically created HTML file, but it is downloaded twice for some reason when I only want the file to be downloaded once.
EDIT ------ Here are the headers
I am trying to export a CSV to the browser using Yii and the CSV keeps being filled by Yii log messages.
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-disposition: attachment; filename=enrollment_course.csv');
$enrollment = Reports::getEnrollment($courseId);
$separator=",";
foreach ($enrollment as $users)
{
$tmp = array(
$users->userid,
$users->firstname,
$users->lastname,
);
echo join($separator, $tmp)."\n";
}
Yii::app()->end();
Any ideas why this doesn't work properly?
yeah, I actually wrote an extension to do that: http://www.yiiframework.com/extension/csvexport/
Basically it amounts to calling exit, take a look at the last few lines of the example:
// options for file, changing delimeter and enclosure
$content = $csv->toCSV('../myfilename.csv', "\t", "'");
Yii::app()->getRequest()->sendFile($filename, $content, "text/csv", false);
// call exit instead of letting sendFile do it, because if you are using
// CWebLogRoute, the onEndRequest event will fire and output your log and not csv file :(
exit();
I would suggest just killing the script after you've output everything. This prevents anything from being added to the output. A simple 'die' should do the trick.
You can use this code in your controller to disable all logging to the browser for all actions:
protected function beforeAction($action)
{
foreach (Yii::app()->log->routes as $route)
{
if ($route instanceof CWebLogRoute)
{
$route->enabled = false;
}
}
return true;
}
source
I am using dompdf to create a pdf file out of an html file that gets created on-the-fly for the sole purpose of it serving as input for the pdf generator, however I am having trouble doing this, I implemented the code in this thread and everything works fine (I could output a simple pdf) however when I try to give it a more specific url I get this error:
An Error Was Encountered Unable to
load the requested file
here's the code that has the problem:
function printPDF(){
//write_file() usa un helper (file)
$this->load->library('table');
$this->load->plugin('to_pdf');
// page info here, db calls, etc.
$query = $this->db->get('producto');
$data['table'] = $this->table->generate($query);
$path_url = base_url().'print/existencias.html';
write_file($path_url, $data['table']);
$html = $this->load->view($path_url, 'consulta', true);
pdf_create($html, 'consulta');
}
Not sure about the exact problem, but please check this:
1) as stated in CI's manual, load->view's second parameter should be an associative array or an objet, translated to vars via extract. That may generate some problem generating $html.
2) try making $path_url relative to application/views directory, as read in CI's manual.
you should use tcpdf to create a pdf.
//create controller for example :
public function create_pdf()
{
$this->load->library("Pdf");
$data['results'] = // your data
$this->load->view('pdfview',$data);
}
//pdfview is the page having tcpdf code and your pdf code.
You can try it like this
public function export_pdf() {
$filename = 'FILENAME.pdf';
header("Content-Description: Advertise Report");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/pdf; ");
$file = fopen('php://output', 'w');
$header = array("Question", "Answer", "Name", "Email", "Phone", "Date");
fputpdf($file, $header);
fputpdf($file, 'YOUR DATA');
fclose($file);
exit;
}