I am trying to create a new CSV file using PHP and upload or move it to a new part of the server but the spreadsheet it returns is a spreadsheet that has only the first cell in the first row with a value of either 404 or 1. What am I doing wrong?
My code is attached below.
// genrate new general spreadsheet
$filepath = substr($file_path, 1);
$data = load_csv_file($filepath);
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="file-saved.csv"');
$fp = fopen('php://output', 'wb');
foreach ($data as $row) {
$output = fputcsv($fp, $row);
}
$filename = "file-saved.csv";
file_put_contents( $filename, $output);
fclose($fp);
The $data variable is an array of values from another CSV file.
$output = [];
foreach($data as $row) {
$output[] = ..
}
...
error_reporting(0);
$file_n = public_path('/csv_file/product_details.csv');
$infoPath = pathinfo($file_n);
if($infoPath['extension'] == 'csv'){
$file = fopen($file_n, "r");
$i = 0;
$all_data = array();
while ( ($filedata = fgetcsv($file, null, "|")) !==FALSE) {
$num = count($filedata );
for ($c=0; $c < $num; $c++) {
$all_data[$i][] = $filedata [$c];
}
$i++;
}
fclose($file);
foreach($all_data as $importData){
$insertData = array(
"article_number"=>$importData[0],
"article_name"=>$importData[1],
"article_description"=>$importData[2],
"article_price"=>$importData[3],
"article_manufacturer"=>$importData[6],
"article_productgroupkey"=>$importData[7],
"article_productgroup"=>$importData[8],
"article_ean"=>$importData[9],
"article_hbnr"=>$importData[10],
"article_shippingcosttext"=>$importData[11],
"article_amount"=>$importData[12],
"article_paymentinadvance"=>$importData[13],
"article_maxdeliveryamount"=>$importData[14],
"article_energyefficiencyclass"=>$importData[15]
);
insertData($insertData);
}
}else{
echo "Invalid file extension.";
}
function insertData($data){
if($article_number->count() == 0){
//write your insert query here for $data
}elseif($article_number->count() > 0){
//article_number already present then update the table.UPDATE QUERY
}
}
Related
I am using PHP for export CSV file this is working, but i export 2000 or greater rows how to create automatic next CSV file.
How to Move other file on after 2000 rows?
<?php
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename = records.csv');
echo $header = "Name";
echo "\r\n";
$sql = mysql_query(“Select * from table”);
while ($getData = mysql_fetch_assoc($sql)) {
echo '"'.$name.'"';
echo "\r\n";
}
exit;
?>
You can use array_chunk function to keep the records of 2000 and export them in csv.
For example
$rowData = [
[1,2,3],
[11,21,31],
[21,22,32],
[31,42,73],
[111,222,333]
];
foreach(array_chunk($rowData, 2) as $key => $records){
$file_name = 'export_data_'.$key.'.csv';
writeToCsv($file_name,$records);
}
//funtion to export data to csv
function writeToCsv($fileName, $rowData){
$fp = fopen($fileName, 'w');
foreach ($rowData as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
In your case use array_chunk($rowData, 2000)
<?php
$rowLimit = 2000;
$fileIndex = 0;
$i = 1;
$handle = null;
$fileList = array();
$timestampFolder = strtotime("now").'/';
mkdir($timestampFolder);
$sql = mysql_query("Select * from table");
while ($getData = mysql_fetch_assoc($sql)) {
if( ($i%$rowLimit) == 1) {
$fileIndex+=1;
if(!is_null($handle)) {
fclose($handle);
}
$fileName = "records".$fileIndex.".csv";
$handle = fopen($timestampFolder.$fileName, "a");
$fileList[] = $fileName;
}
fputcsv($handle, $getData);
$i++;
}
foreach($fileList as $file) {
echo ''.$file.'<br>';
}
I have some code which downloads a CSV file from an S3 bucket into a PHP variable.
I want to get this CSV content (a string) from this variable and convert it into an array.
I'm having some issues reading from my php://memory resource.
When I print the $csv_fread or $rows I see nothing.
Dumping the $csv_fstat shows the correct length of my file I uploaded and then downloaded and put into the $file_contents string and wrote to the $csv resource.
Any help appreciated.
// use Aws\S3\S3Client;
$result = $this->client->getObject([
'Bucket' => $this->bucket,
'Key' => $id
]);
$file_contents = $result['Body'];
$csv = fopen('php://memory', 'r+');
if ($csv === false) {
throw new Exception('Could not create file wrapper');
}
if (fwrite($csv, $file_contents) === false) {
throw new Exception('Could not write contents to file wrapper');
}
$csv_fstat = fstat($csv);
$csv_fread = fread($csv, $csv_fstat['size']);
if ($csv_fread === false) {
throw new Exception('there was an error reading shit');
}
$header = null;
$rows = [];
while (($row = fgetcsv($csv, 0, ',')) !== false) {
if (!$header) {
$header = [];
foreach ($row as $v) {
$header_raw[] = $v;
$hcounts = array_count_values($header_raw);
$header[] = $hcounts[$v] > 1 ? $v . $hcounts[$v] : $v;
}
} else {
foreach ($row as &$l) {
$l = trim($l);
}
$rows[] = array_combine($header, $row);
}
}
fclose($csv);
I figured out the issue. Needed to do:
rewind($csv);
After fwrite
I would like to split a very large CSV file (20 000 lines) to be able to put everything in my MySQL database (after I use cronjob for load the php file every hours).
So I have found code to split my file :
$inputFile = 'Shipping.csv';
$outputFile = 'output';
$splitSize = 1000;
$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);
if ($data)
fputcsv($out, $data);
$rowCount++;
}
fclose($out);
I have tried to do this but they don't work :
require_once dirname(__DIR__).'/pdo.php';
$inputFile = 'Shipping.csv';
$outputFile = 'output';
$splitSize = 1000;
//open uploaded csv file with read only mode
$in = fopen($inputFile, 'r');
//skip first line
fgetcsv($in);
$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);
if ($data){
fputcsv($out, $data);
}
while(($line = fgetcsv($out)) !== FALSE){
//check whether member already exists in database with same email
$prevQuery = "SELECT id FROM shipbp WHERE license = '".$line[1]."'";
$prevResult = $bdd->query($prevQuery);
if($prevResult->rowCount() > 0)
{
$bdd->query("UPDATE shipbp SET license = '".$line[0]."'");
}
else{
$bdd->query("INSERT INTO shipbp (license) VALUES ('".$line[0]."')");
}
}
$rowCount++;
}
fclose($out);
CSV file look like :
P135460,002,00003,250,AS44563,0.35,,Blabla,17/3/2017 00:00:00,SB,Blabla
How I can do ?
Thank you for your help
First of all I load PHPExcel.php
Secondly, I am using this code:
$location = '/path/file.csv';
$inputFileType = 'CSV';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($location);
$worksheet = $objPHPExcel->getActiveSheet();
$list = array();
foreach ($worksheet->getRowIterator() as $row)
{
$rowIndex = $row->getRowIndex();
$cellValue = $worksheet->getCell('A'.$rowIndex)->getValue();
array_push($list, $cellValue);
}
$count = count($list);
for ($rowIndex = $count; $rowIndex != 1; $rowIndex--)
{
$cellValue = $worksheet->getCell('A'.$rowIndex)->getValue();
for ($i = $rowIndex - 2; $i != 0; $i--)
{
if ($list[$i] == $cellValue)
{
$worksheet->removeRow($rowIndex);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($location);
break;
}
}
}
So, I am trying to remove the rows when there are duplicate values in the first column. The code does not work. When I first run it in putty, I have to wait for ages. I interrupt the process and then I run it again. Then it runs, but in my csv file I have wrong results (duplicates are 300 but I am getting -600 rows).
In order to read a CSV file you dont have to use PHPExcel. Instead you can use a native php code like this one:
<?php
// Array which will hold all analyzed lines
$uniqueEntries = array();
$dublicatedEntries = array();
$delimiter = ',';
$file = 'test.csv';
//Open the file
if (($handle = fopen($file, "r")) !== false) {
// read each line into an array
while (($data = fgetcsv($handle, 8192, $delimiter)) !== false) {
// build a "line" from the parsed data
$line = join($delimiter, $data);
//If the line content has ben discovered before - save to duplicated and skip the rest..
if (isset($uniqueEntries[$line])){
dublicatedEntries[] = $line;
continue;
}
// save the line
$uniqueEntries[$line] = true;
}
fclose($handle);
}
// build the new content-data
$contents = '';
foreach ($uniqueEntries as $line => $bool) $contents .= $line . "\r\n";
// save it to a new file
file_put_contents("test_unique.csv", $contents);
?>
This code is untested but should work.
This will give you a .csv file with all unique entries.
I have the following query running and I am looking at the best way to export the data to a .csv or .xls file.
<?php
$channels = ee()->db->select('channel_titles.entry_id, channel_titles.title, channel_data.field_id_164')
->from('channel_titles')
->join('channel_data', 'channel_titles.entry_id = channel_data.entry_id')
->where(array(
'channel_titles.channel_id' => '12',
))
->or_where(array(
'channel_titles.channel_id' => '31',
))
->get();
if ($channels->num_rows() > 0)
{
$i = 0;
foreach($channels->result_array() as $row)
{
$i++;
echo $row['field_id_164'].",".$row['title']."<br />\n";
}
echo $i;
}
?>
I have tried a few methods but cannot seem to figure out the best option.
The classic echo explode(',',$col) etc way is fine, but you can also write directly to the csv file using php's built in functions.
$filename = 'test.csv';
$file = fopen($filename,"w");
if ($channels->num_rows() > 0) {
foreach($channels->result_array() as $key => $row) {
if ($key==0) fputcsv($file, array_keys((array)$row)); // write column headings, added extra brace
foreach ($row as $line) {
$line = (array) $line;
fputcsv($file, $line);
}
}
}
fclose($file);
edit:
If you want to download/view the file instantly you have to set the headers.
$filename = 'test.csv';
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$file = fopen('php://output', 'a');
if ($channels->num_rows() > 0) {
foreach($channels->result_array() as $key => $row) {
if ($key==0) fputcsv($file, array_keys((array)$row)); // write column headings, added extra brace
foreach ($row as $line) {
$line = (array) $line;
fputcsv($file, $line);
}
}
}
fclose($file);