Merge csv files [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to merge multiple CSV files in to one csv files in PHP or joomla?
Merge all data from the csv files in a folder into a text file
with a few small changes you can also use this for txt files. Replace *.csv for *.txt

To do this in PHP you would do something in the lines of:
Open a file handle where the merged csv data can be written to
Read all the filenames from the source dir
For every file that ends with ".csv", append its content to the merge file
Ex.
$csvdir = './csvdir';
$result = fopen('./merge.csv', 'w');
if ($handle = opendir($csvdir)) {
while (false !== ($entry = readdir($handle))) {
if (substr($entry, -4) === ".csv") {
$csvcontent = file_get_contents($entry);
fwrite($result, $csvcontent);
}
}
closedir($handle);
}
fclose($result);

Merge all data from the csv files in a folder into a text file
Note: with a few small changes you can also use this for txt files. Replace *.csv for *.txt
1) Windows Start Button | Run
2) Type cmd and hit enter ("command" in Win 98)
3) Go to the folder with the CSV files (for help how to do that enter "help cd")
4) Type copy *.csv all.txt and hit enter to copy all data in the files into all.txt.
5) Type exit and hit enter to close the DOS window
Now we must import the text file all.txt into Excel.
1) Open Excel
2) When you use File Open to open all.txt the Text Import Wizard will help you import the file
3) Choose Delimited
4) Next
5) Check Comma
6) Finish

Related

Delete all files with a php script [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I delete all files with a PHP script on a server? My problem is that I have many files that need to be deleted and over the FTP client it takes quite a long time.
you can delete all files using for loop, example:
`
$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
`
Untested but this should work:
$dir = "dir/to/purge/"; // Directory you want to remove all the files from
$listing = scandir($dir); // Array containing all files and directories inside the provided directory
foreach($listing as $file) {
if(is_file($dir . $file)) {
unlink($dir . $file); // Removes the file from the listing
}
}
Note that with a lot of files this could use up all your memory.

Create multiple CSV file with PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm following this answer to create a csv file with PHP. But how can I create multiple csv files? Everyone said that those csv files must be sent into zip file. But I don't know how to.
I tried to double the code to make 2 csv files, and then add this at the end, but the zip contains nothing after I downloaded it.
Firstly you will need to create the ZIP folder, create and save each CSV to a temporary location, then add them to the ZIP, delete the temporary CSV file, and finally download the ZIP.
As I don't know what code you're working with exactly here is some code that you should be able to put into your project
// create the ZIP file
$zip_name = 'csv.zip';
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);
$files = array('file_1.csv', 'file_2.csv', 'file_3.csv');
$temp_directory = 'path to directory';
// create each CSV file and add to the ZIP folder
foreach($files as $file) {
$handle = fopen($temp_directory . $file, 'w');
$data = array(); // data maybe from MySQL to add to your CSV file
// add your data to the CSV file
foreach($data as $d) {
fputcsv($handle, $d);
}
fclose($handle);
// add this file to the ZIP folder
$zip->addFile($temp_directory . $file);
// now delete this CSV file
if(is_file($temp_directory . $file)) {
unlink($temp_directory . $file);
}
}
$zip->close();

PDF in PHP ZipArchive throwing errors, server permissions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am collecting a number of files from the server and generating a ziparchive with PHP. All goes super well until I download the zip archive and try to open the file. The reader throws an exception "File type plain text document (text/plain) is not supported". The file is named correctly (c102.pdf). I presume the mime type of the file is getting messed up some how, but I'm not quite sure.
php version 5.4.37
I should note that I'm using ubuntu 14.04 locally and my reader is the default document viewer, however, it does read the file correctly before upload.
follow up - Could this be a permissions issue? the "downloads" directory is set to 777, while the new zip files created within it are 644. Its as if "blank" files are being placed in the zip archive (the total size of the zip is 1.6k and should be at least a few hundred).
Another follow up - the following previous posts discuss the chmod issue
PHP: generated zip has chmod 644 and how to set permission 777 to a zip file? . The chmod() method is not working for me however - chmod() fails to execute on the server (I've amended the code below). We will see what technical support has to say.
Answer in this case.....
After speaking to Customer Support - the reason none of this is working is because I'm on a shared hosting account. The chmod() function is restricted and should otherwise work.
My saga continues...
I now have a LAMP stack on an EC2 instance and just when I thought I was boss - I remain in the same bind. My program generates a zip file in the correct directory - with all the appropriate file names - but the files are empty. I am still thinking this is an ownership / permissions issue. SO, some follow up questions...
The folders on the web server are owned by "Ubuntu", yet the newly created files are owned by "www-data". So, who is "www-data"? is it Apache or PHP? is PHP also Apache? why cant I chmod() the files after their created so they aren't 644? Is the files status of the zip as 644 the reason I can't write to them? Can I force newly created files in a directory to have different ownership or a particular set of permissions?
if (isset($_GET['getzip'])) {
$issuedsetid = $_GET['getzip'];
$time = mktime();
$sql = "SELECT * FROM issuedsets WHERE id=$issuedsetid";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
$packid = $row['packid'];
$sheets = $row['sheets'];
$sheets = explode(",",$sheets);
}
}
$sql = "SELECT * FROM pname WHERE id=$packid";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
$packname = $row['name'];
}
}
// create the zip file
$path = "/home/marekfalkowski/public_html/index/downloads/".$packname."_" . $time . ".zip";
$zip = new ZipArchive();
// Open a new zip file
$zip->open($path, ZipArchive::CREATE);
if (chmod($path,0777)){
echo "chmod succesful";
} else {
echo "not succesful";
}
foreach($sheets as $sheet){
// the saved file name as it exists on the server...
$file = $sheet.".pdf";
// the new name of the file...
$sql = "SELECT * FROM files WHERE id=$sheet";
if ($result = $mysqli->query($sql)) {
while($row = $result->fetch_assoc()) {
$filename = $row['number']."-".$row['name'].".pdf";
}
}
// add the files
if (file_exists("/home/marekfalkowski/public_html/index/uploads/".$file)) {
$zip->addFile("/home/marekfalkowski/public_html/index/uploads/".$files, $filename);
} else {
echo "not there";
}
}
$zip->close();
}
This was a silly mistake. This line:
$zip->addFile("/home/marekfalkowski/public_html/index/uploads/".$files, $filename);
needs to be changed to this:
$zip->addFile("/home/marekfalkowski/public_html/index/uploads/".$file, $filename);
What a waste of time this has been. It works now.

How to assign a value to a variable from a text file? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using a script to back up files from ftp. code is below.
include "recurseZip.php";
//Source file or directory to be compressed.
$src='source/images/black.png';
//Destination folder where we create Zip file.
$dst='backup';
$z=new recurseZip();
echo $z->compress($src,$dst);
Now I want to get values to $src from source/files.txt which contains a list of file names.
My .txt file:
index.php.bk-2013-12-02
index.php.bk-2013-12-07
index.php.bk-2013-12-10
index.php.bk-2013-12-20
index.php.bk-2013-12-26
function.php.bk-2013-12-20
function.php.bk-2013-12-23
contact.php.bk-2013-12-23
contact.php.bk-2013-12-30
my source/files.txt contains 10 file names those need to be assigned as values to the variable $src I am using this script http://ramui.com/articles/php-zip-files-and-directory.html
how can I do that.?
any help will be very much appreciated.
Thanks.
Okay, you want to get the file name from each line of the .txt file.
<?php
$myFile = "files.txt";
$lines = file($myFile);
foreach($lines as $line){
$file = basename($line);
echo $file;
}
?>
Answer to your old question variant
You can use the basename() function. The manual says, "given a string containing the path to a file or directory, this function will return the trailing name component".
Now, you said "I want to get file name to $src from source/files.txt", so assuming from this, you are looking to get the file name i.e. black.png. This could be achieved using the basename() function as mentioned before.
<?php
$src='source/images/black.png';
$file = basename($src);
echo $file;
?>
Output
black.png
http://ideone.com/p2b4sr

Running hundreds of files through single PHP script [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to run 600 XML files through a script I've made that extracts specific pieces of information and saves each one in JSON format. All 600 XML files are inside a folder ready to be run through the PHP file, I'm now looking for a fast way to do it.
Essentially this is the process the PHP file goes through:
PHP reads single XML file via URL -> locally saves important info in variables -> saves important info into JSON file
Is there a way I can somehow run all 600 XML files through my PHP file?
Thanks
Open the directory containing the XML files and then process them, here are some of the most common way todo that.
opendir()
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
You can also use glob()
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Inside the foreach loop of whichever you choose you can use file_get_contents() or fread() then you can do your conversion to json.
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Hope it helps
Just go ahead and try! You'll probably run into a timeout error. If you do, try configuring the max timeout settings. http://php.net/manual/en/function.set-time-limit.php
Joel,
Sounds to me like what you need to is to use readdir
http://php.net/manual/en/function.readdir.php
This will allow you to get a list of files in a directory to iterate over.
$dir = opendir('/path/to/files');
while($file = readdir($dir)) {
if ($file !== '.' && $file !== '..' && !is_dir($file)) {
$parthParts = pathinfo($file);
if ($pathParts['extension'] === 'xml') {
runscripton($file);
}
}
}
closedir($dir);
First, write a function that gets an XML file name, and after processing, returns the results in php array or JSON (Based on how you need your code to be).
To write this function, you need to parse XML (http://php.net/manual/en/book.xml.php).
To work with JSON in PHP: http://php.net/manual/en/book.json.php
Then, write your main code. Your main code should enumerate all XML files in the folder, and then call your function for each file, and gather/generate JSON using information returned by the function.
You might need readdir to gather all of XML files in the folder. (http://php.net/manual/en/book.xml.php)
Don't forget to increase time limit as long as there are lots of XML files and the process might take long so a timeout error would occur. (http://php.net/manual/en/function.set-time-limit.php)

Categories