File empty after fputcsv - php

I created a file with fputcsv
$handle = fopen('php://output', 'w+');
// Add the header of the CSV file
fputcsv($handle, array('Name', 'Surname', 'Age', 'Sex'), ';');
// Query data from database
// Add the data queried from database
foreach ($results as $result) {
fputcsv(
$handle, // The file pointer
array(...), // The fields
';' // The delimiter
);
}
file_put_contents('mycsv.csv',fgetcsv($handle), FILE_APPEND);
fclose($handle);
....
I want to save the output on mycsv.csv but the file is empty

The php://output is a stream that works like echo or print. It means, you are writing in the standard output (maybe, your console or the browser).
If you want to write your content in a csv file, try to open this file or create it using PHP directly, instead of use the file_put_contents.
$handle = fopen("mycsv.csv","wb");
fputcsv($handle, array('Name', 'Surname', 'Age', 'Sex'), ';');
//...put your code
rewind($handle);//optional.it will set the file pointer to the begin of the file

Related

Add new row in CSV using PHP

I want to append form data in a CSV file that is stored on the server, the data should be added as a new row.
I tried
$list = array(
'Peter,Griffin,Oslo,Norway,Norway,Norway,Norway,Norway',
'Glenn,Quagmire,Oslo,Norway,Norway,Norway,Norway,Norway',
);
print_r($list);
$file = fopen('db.csv','a'); // 'a' for append to file - created if doesn't exit
foreach ($list as $line){
fputcsv($file,explode(',',$line));
}
fclose($file);
but can't add data at the end of the file.
How can i achieve this?
You should open your CSV file in append mode fopen(FILENAME, 'a'); before calling fputcsv():
<?php
define('FILENAME', 'file.csv');
$lines = [
['aaa', 'bbb', 'ccc'],
['123', '456', '789'],
['Quotes " get repeated twice', 'If commas , then it will be surounded by quotes', 'ccc'],
];
// Fill the CSV file.
$file = fopen(FILENAME, 'w');
foreach ($lines as $fields) {
fputcsv($file, $fields);
}
fclose($file);
// Add a new line at the end of the file
$file = fopen(FILENAME, 'a');
fputcsv($file, ['another', 'line', 'at the end']);
fclose($file);
?>
It's important that you have write permission on the CSV file if not you won't be able to append data to it. The user and group of the file may not be the same as the PHP process. This depends a lot on your hosting service. The best would be to check that your SSH or FTP user is in the same group than the PHP running your web site. If both are in the same group then you can just give write permission to the user and group and only read for other users:
chmod ug=rw,o=r db.csv
Or even no read permission to other users, which would be even better:
chmod ug=rw,o= db.csv
Up to you to see what's the best to do. You can also change the user and group of the file with chown username db.csv or chgrp groupname db.csv or even chown username:groupname db.csv.
Your code where I replaced the explode(',', $line) by preg_split('/\s*,\s*/', $line) in order to handle eventual spaces around the comma character:
<?php
// Just to see the var_export() in plain text instead of HTML.
header('Content-Type: text/plain;charset=utf-8');
// With spaces or tabs around the commas for the preg_split() demo.
$lines = array(
"Peter,\tGriffin,Oslo, Norway,Norway ,Norway, Norway,Norway",
'Glenn, Quagmire, Oslo, Norway, Norway, Norway, Norway, Norway',
);
var_export($lines);
$file = fopen('db.csv', 'a');
foreach ($lines as $line) {
fputcsv($file, preg_split('/\s*,\s*/', $line));
}
fclose($file);
?>

Export HTML table to CSV file

I am making a script which gets a table from your mail and puts it into a CSV file.
This is the code I use to transfer my html table to CSV
$html = str_get_html($outputstr);
// For Excel
header('Content-type: application/ms-excel');
// Download File
header('Content-Disposition: attachment; filename=sample.csv');
$fp = fopen("php://output", "w");
// Take out empty lines
foreach($html->find('tr') as $element) {
$td = array();
foreach( $element->find('th') as $row) {
$td [] = $row->plaintext;
}
foreach( $element->find('td') as $row) {
$td [] = $row->plaintext;
}
fputcsv($fp, $td);
}
fclose($fp);
The only problem that I'm getting is that when I am opening the CSV file, some of the empty columns have a strange character:
I cannot read through with my PHP script to export it to a database
fgetcsv($handle, 1000, "\t");
How can I fix this problem?
Do I fix this by modifying the code on the part where I create the CSV file or where I read the CSV file when I'm transferring it to a MySQL database?
When I use an online html to CSV converter it works fine and I am not facing this issue then.
If there is any code needed then I'd love to share it.
Any help would be appreciated.
Have you tried setting your charset to UTF-8? Additionally, you're not setting this up as a CSV with your header, instead it is an Excel file.
header("content-type:application/csv;charset=UTF-8");

Save generated csv file to sub folder with php

I have tried to store the created csv file to another subfolder instead of getting stored where the php-file is located but with no luck. Have anyone solved this by changing fopen? This is my code:
<?php
$data_array = array (
array ('test', $_POST['test'],)
);
$csv = "col1,col2 \n";//Column headers
foreach ($data_array as $record){
$csv.= $record[0].','.$record[1]."\n"; //Append data to csv
}
$csv_handler = fopen ('order_'.date('m-d-Y_hia').'.csv','w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
echo 'Data saved to csvfile.csv';
?>

Remove first line in CSV and then save the file overwriting existing

I have a CSV file which is generated dynamically. I want to remove the first line of CSV and then save it again.
I have googled and was able to get first line of csv but the part of writing it again after removing is where I am stuck.
Here is example
line1,data1
line2,data2
line3,data3
What I want to acheive
line2,data2
line3,data3
That is first line removed and file saved again
Here is my code
$file = fopen('words.csv', 'r');
$data = fgetcsv($file,10000,",");
$data = array_shift($data);
$file = fopen('words.csv', 'w');
fputcsv($file,$data,",");
fclose($file);
I get this:
! ) Warning: fputcsv() expects parameter 2 to be array, string given in C:\wamp\www\scrape\test.php on line 7
And output file is empty.
Ahmar
// Read the file
$file = fopen('words.csv', 'r');
// Iterate over it to get every line
while (($line = fgetcsv($file)) !== FALSE) {
// Store every line in an array
$data[] = $line;
}
fclose($file);
// Remove the first element from the stored array / first line of file being read
array_shift($data);
// Open file for writing
$file = fopen('words.csv', 'w');
// Write remaining lines to file
foreach ($data as $fields) {
fputcsv($file, $fields);
}
fclose($file);
You have some errors in your code. The first one is that fgetcsv function only gets one line so if you want to extract all the lines you need a loop. The same happens with fputcsv function.
The other one is that array_shift function returns the shifted value so you are assigning to $data the string you don't need.
So, I think your code must be like:
$file = fopen('words.csv', 'r');
$data=array();
while (($data_tmp = fgetcsv($file, 1000, ",")) !== FALSE) {
$data[] = $data_tmp;
}
fclose($file);
array_shift($data);
$file = fopen('words.csv', 'w');
foreach($data as $d){
fputcsv($file,$d);
}
fclose($file);

How to replace one line in php?

I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/

Categories