Exporting CSV printing HTML - php

I am trying to export CSV using PHP. But instead of printing the result it's printing Resource id #26 in the generated CSV FILE. If I remove exit from end it print's my whole HTML page content. My code is...
if (isset($_REQUEST['download']) && ($_REQUEST['download'] == "yes")) {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=link_point_report.csv');
$output = fopen('php://memory', 'w+');
fputcsv($output, array('Member Id', 'Customer Name', 'Customer Email'));
$customerListAll = $oAdmFun->linkpoint_check_customer('', '');
$oAdmFun->pr($customerListAll, true);
// if (count($customerListAll) > 0) {
// for ($c = 0; $c < count($customerListAll); $c++) {
// fputcsv($output, array('Sankalp', 'Sankalp', 'Sankalp'));
// }
// }
ob_clean();
flush();
exit($output);
}

That's because $output is a resource, which is what fopen() returns. You need to use fread() to get its contents.
EDIT: Now I understand what you were asking. To output the contents of your CSV, you need to get the text output from the resource:
rewind( $output );
$csv_output = stream_get_contents( $output );
fclose( $output );
die( $csv_output );
And it's also a good idea to set the content-length header so that the client knows what to expect:
header('Content-Length: ' . strlen($csv_output) );

Open a chunk of writable memory:
$file = fopen('php://temp/maxmemory:'. (12*1024*1024), 'r+'); // 128mb
Write to it... then fetch the contents with:
rewind($file);
$output = stream_get_contents($file);
fclose($file);

function CSV_HtmlTable($csvFileName)
{
// better to open new webpage
echo "<html>\n<body>\n\t<table style=''>\n\n";
$f = fopen($csvFileName, "r");
$trcount = 0; //start the row count as 0
while (($line = fgetcsv($f)) !== false) {
$trclass = ''; if ($trcount%2==0) { $trclass=' class="dark"'; } //default to nothing, but if it's even apply a class
echo "\t\t<tr".$trclass.">\n"; //same as before, but now this also has the variable $class to setup a class if needed
$tdcount = 0; //reset to 0 for each inner loop
foreach ($line as $cell) {
$tdclass = ''; if ($tdcount%2==0) { $tdclass=' class="dark"'; } //default to nothing, but if it's even apply a class
echo "\t\t\t<td ".$tdclass."style='padding:.4em;'>" . htmlspecialchars($cell) . "</td>"; //same as before, but now this also has the variable $class to setup a class if needed
$tdcount++; //go up one each loop
}
echo "\r</tr>\n";
$trcount++; //go up one each loop
}
fclose($f);
echo "\n\t</table>\n</body>\n</html>";
}

Related

Why is my csv splitting script returning extra rows before the header?

I have a csv file that I download periodically. The CSV expects to be split, so it is split up in chunks of 5000, including the header at the top of each split csv.
This means my header lines are at 1, 5001, 10002, 15003, 20004, etc...
I have written a php script to do the job of splitting the file, however I can't seem to capture the pattern to include the header ONLY at the header.
<?php
$inputFile = 'import.csv';
$outputFile = 'output_';
$splitSize = 5000;
$in = fopen($inputFile, 'r');
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
}
$data = fgetcsv($in);
var_dump($data);
fputcsv($out, $data);
$rowCount++;
}
}
fclose($out);
The problem here is that by the third file, I am getting an extra line of data at the top of each file which should have been printed into the previous file.
This would lead me to believe that I need my chunks to be 5001 lines in size instead, but if I provide 5001 as the splitsize parameter, I get the opposite. The first file contains the header at line 1 and 5001.
I'd love to just split the file anywhere the header is detected, so if $data[0] is equal to 'Action', split the file, but I'm kind of lost at how to accomplish that as well.
Since you would prefer to split if $data[0] == 'Action', this is what I would suggest:
while (!feof($in)) {
$data = fgetcsv($in);
if ($data[0] == 'Action') {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
}
fputcsv($out, $data);
$rowCount++;
}

PHP data processing not outputting

Hi I am trying to get this external text file to print inside my php document. The code looks fine to me however when I echo it does not output anything and I am not sure why this is. Can anybody help me out as I am new to this.
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
$fp = fopen($location, 'r');
if ($fp) {
$readin = fread($fp);
fclose($fp);
} else {
echo 'Can\'t open input.txt';
}
Not sure what you're trying to 'echo' but have you checked if the file exists in the first place?
Your code could be written as:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location) && $data = file_get_content($location)){
echo $data;
} else {
echo 'File not found';
}
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} esle {
echo 'File not found';
}
See here for more: http://php.net/manual/en/function.file-get-contents.php, http://php.net/manual/en/function.filesize.php

Create CSV from data returned from API

I'm trying to use Mailchimp's Export API to generate a CSV file of all members of a given list. Here' the documentation and the example PHP code they give:
$apikey = 'YOUR_API_KEY';
$list_id = 'YOUR_LIST_ID';
$chunk_size = 4096; //in bytes
$url = 'http://us1.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id;
/** a more robust client can be built using fsockopen **/
$handle = #fopen($url,'r');
if (!$handle) {
echo "failed to access url\n";
} else {
$i = 0;
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
if ($i==0){
//store the header row
$header = $obj;
} else {
//echo, write to a file, queue a job, etc.
echo $header[0].': '.$obj[0]."\n";
}
$i++;
}
}
fclose($handle);
}
This works well for me and when I run this file, I end up with a bunch of data in this format:
Email Address: xdf#example.com
Email Address: bob#example.com
Email Address: gerry#example.io
What I want to do is turn this into a CSV (to pass to a place on my server) instead of echoing the data. Is there a library or simple syntax/snippit I can use to make this happen?
If the format simply like:
Email Address, xdf#example.com
Email Address, bob#example.com
Email Address, gerry#example.io
is what you after, then you can do:
$handle = #fopen($url,'r');
$csvOutput = "";
if (!$handle) {
echo "failed to access url\n";
} else {
$i = 0;
$header = array();
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
if ($i==0){
//store the header row
$header = $obj;
} else {
//echo, write to a file, queue a job, etc.
echo $header[0].', '.$obj[0]."\n";
$csvOutput .= $header[0].', '.$obj[0]."\n";
}
$i++;
}
}
fclose($handle);
}
$filename = "data".date("m.d.y").".csv";
file_put_contents($filename, $csvOutput);
The variable $csvOutput contains the CSV format string.
This ones on me. From now on you might want to actually read some documentation instead of copying and pasting your way through life. other's will not be as nice as i am. here's a list of file system functions from the php website. http://php.net/manual/en/ref.filesystem.php Getting the file output to the desired csv format is an exercise left to the reader.
$apikey = 'YOUR_API_KEY';
$list_id = 'YOUR_LIST_ID';
$chunk_size = 4096; //in bytes
$url = 'http://us1.api.mailchimp.com/export/1.0/list?apikey='.$apikey.'&id='.$list_id;
/** a more robust client can be built using fsockopen **/
$handle = #fopen($url,'r');
if (!$handle) {
echo "failed to access url\n";
} else {
$i = 0;
$header = array();
$output = ''; //output buffer for the file we are going to write.
while (!feof($handle)) {
$buffer = fgets($handle, $chunk_size);
if (trim($buffer)!=''){
$obj = json_decode($buffer);
if ($i==0){
//store the header row
$header = $obj;
} else {
//write data into our output buffer for the file
$output .= $header[0].': '.$obj[0]."\n";
}
$i++;
}
}
fclose($handle);
//now write it to file
$path = '/path/to/where/you/want/to/store/file/';
$file_name = 'somefile.csv';
//create a file resource to write to.
$fh = fopen($path.$file_name,'w+');
//write to the file
fwrite($fh,$output);
//close the file
fclose($fh);
}

Doctrine2 Batch processing

I'm trying to import text file with 10000+ lines into DB. I've found a manual here. But my script ends just before reaching the final flush without any error. The boolean parameter in my custom flush method stands for calling clear method after flushing.
Code:
$handle = fopen($file, 'r');
if ($handle != FALSE) {
// Clear entities
$clear = 1;
// Read line
while (($data = fgets($handle)) !== FALSE) {
$entity = $this->_createEntity($data);
echo $clear . '<br>';
$this->getPresenter()->getService('mapService')->persist($entity);
if ($clear % 100 == 0) {
echo 'saving...<br>';
$this->getPresenter()->getService('mapService')->flush(TRUE); // Flush and clear
}
$clear++;
}
echo 'end...'; // Script ends before reaching this line
$this->getPresenter()->getService('mapService')->flush(); // Final flush
echo '...ed';
}
fclose($handle);
Custom Flush method:
public function flush($clear = FALSE) {
$this->db->flush();
if ($clear) {
$this->db->clear();
}
}
Echo output:
1
...
9998
9999
10000
saving...
But no end......ed.
Thanks a lot in advance.
EDIT
I've changed number of line in files to process in one batch from 10k to 5000. It's OK now. But I still wonder why 10k is "too much" for PHP or Doctrine.
Try using feof:
$handle = fopen($file, 'r');
if ($handle != FALSE) {
// Clear entities
$clear = 1;
// Read line
//while (($data = fgets($handle)) !== FALSE) {
while (!feof($handle)){
$data = fgets($handle);
$entity = $this->_createEntity($data);
echo $clear . '<br>';
$this->getPresenter()->getService('mapService')->persist($entity);
if ($clear % 100 == 0) {
echo 'saving...<br>';
$this->getPresenter()->getService('mapService')->flush(TRUE); // Flush and clear
}
$clear++;
}
echo 'end...'; // Script ends before reaching this line
$this->getPresenter()->getService('mapService')->flush(); // Final flush
echo '...ed';
}
fclose($handle);

create multiple directories using loop in php

I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
while ( $line < 5 )
{
$a = fgets($f, 100);
$nl = mb_strtolower($line);
$nl = "checkmeck/".$nl;
$nl = $nl."faraz"; // it works for static value i.e for faraz
//$nl = $nl.$a; // i want this to be the name of folder
if (!file_exists($nl)) {
mkdir($nl, 0777, true);
}
$line++;
}
kindly help
use feof function its much better to get file content also line by line
Check this full code
$file = __DIR__."/dataFile.txt";
$linecount = 0;
$handle = fopen($file, "r");
$mainFolder = "checkmeck";
while(!feof($handle))
{
$line = fgets($handle);
$foldername = $mainFolder."/".trim($line);
//$line is line name daa1,daa2,daa3 etc
if (!file_exists($foldername)) {
mkdir($foldername, 0777, true);
}
$linecount++;
unset($line);
}
fclose($handle);
output folders
1countfaraz
2countfaraz
3countfaraz
Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():
$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$nl = "checkmeck/". $line;
if (!file_exists($nl)) {
echo 'Creating file '. $nl . PHP_EOL;
mkdir($nl, 0777, true);
echo 'File '. $nl .' has been created'. PHP_EOL;
} else {
echo 'File '. $nl .' already exists'. PHP_EOL;
}
}
The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.
So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:
daa1
daa2
daa3
...then it should create the following folders:
checkmeck/daa1
checkmeck/daa2
checkmeck/daa3

Categories