I have a CSV list which contains URL/Link of some image.
So I had tried this below code;
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
col1 = $col[0];
for ($i = 0; $i < count($col1); $i++){
if ( !$col1[$i] == null){
echo $col1[$i]. ",<br>";
file_put_contents("images/img.jpg", $elements[$i] . "\n", FILE_APPEND);
}
}
}
fclose($handle);
}
the code is working, but it's replacing the image at the end of execution I'm getting only one pic which's Last row of csv & Getting error Max_execution time.
Try this out.
$handle = fopen($csv_file, "r");
$destination = 'images/';
if ($handle) {
while ($columns = fgetcsv($handle)) {
foreach ($columns as $imageUrl) {
if (!empty($imageUrl)) {
file_put_contents(
$destination . basename($imageUrl),
file_get_contents($imageUrl)
);
}
}
}
}
What it does is open the CVS, loops through it, row at a time, checks that the image URL isn't empty, downloads it and puts it into your directory. You of course need to make sure that PHP has the rights to write to that directory. The code also doesn't handle conflicts in the naming of images, so a further improvement would be to add some clash detection and append a counter before the suffix.
Related
I am trying to import 6 files which are in zip files. First I extract those files after that I want to get all the data in these files. But currently I am getting only the first file data. The script had not read the second file. I don't understand how to get rid from this problem.
Here is my code.
<?php
if ($_FILES) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array(
'application/zip',
'application/x-zip-compressed',
'multipart/x-zip',
'application/x-compressed'
);
foreach ($accepted_types as $mime_type) {
if ($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if (!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "zip/" . $filename;
if (move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
$col = array();
if ($x === true) {
for ($x = 0; $x < $zip->numFiles; $x++) {
$csv = $zip->getNameIndex($x);
$zip->extractTo("zip/");
$csv_path = "zip/" . $csv;
if (($handle = fopen($csv_path, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c = 0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
echo "<pre>";
print_r($col);
}
fclose($handle);
}
}
$zip->close();
unlink($target_path);
exit;
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
Any help would be Highly appreciated.
Look at this part of your code...
<?php
// ...code...
$zip->extractTo("zip/");
$csv_path = "zip/" . $csv;
if (($handle = fopen($csv_path, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// ...code...
?>
extractTo() extracts the files. There are six files, you said. Then you do fopen(), and you do it once. You want to do that fopen() on each of the files.
What you'll want is...
<?php
// ...code... (files are extracted at this point)
$files = files('zip/');
for($i = 0; i < count($files); $i++) {
$file = $files[$i];
// ...do csv stuff here for $file
}
// ...code...
?>
I have six CSV files that I want to convert into individual arrays and then intersect those arrays to see all of the values that are similar in each. I have this so far:
$directory = "/csv/CSS_AUDIT/";
if (! is_dir($directory)) {
exit('Invalid directory path');
}
$files = array();
foreach (scandir($directory) as $file) {
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
$row = 1;
if (($handle = fopen("/csv/CSS_AUDIT/$file", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($r=0; $r < $num; $r++) {
echo $data[$r];
if (!empty($data[$r]))
echo "\n";
}
}
fclose($handle);
}
}
Right now it is looping through the files and giving me everything in one large array and I'm just kinda stuck. Any advice on how to achieve What I am trying to do?
If the files aren't too big, you can load them into an array and either check that such value doesn't exist in the array before adding to it, or running array_unique() when you're done. See this for a reference.
If the files are too big, you'll have to use some other more complicated and time-consuming methods (such as reading the (hopefully sorted) output each time before inserting new line).
Variables:
$csvFile = $_FILES['uploadfile']['tmp_name'];
$csvFile = $con->real_escape_string($csvFile);
$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv','csv');
if statement:
if(in_array($csvFile, $mimes))
{
$file = fopen($csvFile, 'r');
$i = 0;
$row = 1;
while (($line = fgetcsv($file)) !== FALSE)
{
if($row == 1){ $row++; continue; }
$data_array[$i] = $line[0];
$data_array[$i] = mysqli_real_escape_string($con, trim($data_array[$i]));
$encrypted_numbers[$i] = encryption::encrypt($data_array[$i]);
$encrypted_numbers[$i] .= mysqli_real_escape_string($con, trim($line[1]));
$i++;
}
fclose($file);
}
else
{
die("Sorry, file type not allowed");
};
I've been trying stuff for 30 min, anyone know why I always get false even if the file is named csv.csv?
$_FILES['uploadfile']['tmp_name'];
you should be looking in 'type' not 'tmp_name'
$_FILES['uploadfile']['type'];
However, there is an SO discussion here about why a csv file can have the application/octet-stream mime-type. It suggests that you need to verify the file-type yourself, and not rely on ['type']. The best way would be to use fgetcsv() to try to parse it as csv. If this fails then assume it is not a csv.
I have a table name tblstuden. It contains ids studentname, rollnumberm and classname. I want to download this data in CSV format. How is it possible?
I can upload the data into the table by CSV file. To upload the code is below. It's working for me. But now I want to download the data in CSV format.
<?php
if(isset($_POST['submit']))
{
$row = 1;
$file1 = $_FILES['file']['tmp_name'];
$file = fopen($file1, "r");
while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
$data[$c];}
echo $data[0];
$name = $data[0];
}
fclose($file);
?>
You can download a csv file using this code.
$getRecord = mysql_query("SELECT id, studentname, rollnumber, classname FROM tblstuden");
while ($row = mysql_fetch_array($getRecord )) {
$csvFile .= $row['id'].",". $row['studentname'].",". $row['rollnumber'].",".$row['classname']."\r\n";
}
header("Content-type: application/octet-stream");
header("Content-disposition:attachment; filename="."testCSV.csv");
echo $csvFile;
I have the following files:
1.jpg
2.jpg
3.jpg
4.jpg
When I remove 2.jpg, I want 3.jpg to become 2.jpg and 4.jpg to become 3.jpg
I tried a for loop with the rename function, but it does not seem to work:
for($a = $i;$a < $filecount;$a ++)
{
rename('photo/'.($a+1).'.jpg', 'photo/'. ($a).'.jpg');
}
Where $i is the number of the photo I just deleted.
List all files, sorted by name:
$files = glob('../photos/*');
Foreach file, rename it if necessary:
foreach($files as $i => $name) {
$newname = sprintf('../photos/%d.jpg', $i+1);
if ($newname != $name) {
rename($name, $newname);
}
}
Why don't you just remove the file you don't longer need and than rename all files that remain in the folder, starting with one. Like:
<?php
$fileToRemove= '3.jpg';
unlink($fileToRemove);
$cnt = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
rename($file, ++$cnt+".jpg");
}
}
closedir($handle);
}
?>
This way, you are always sure that the sequence is correct. If you have a lot of files, you can of cource start renaming from the number of the file you are deleting.
I would have do it this way:
echo "<pre>";
$files = array('file1.jpg', 'file5.jpg', 'file7.jpg', 'file9.jpg');
function removeElement($array, $id){
$clone = $array; // we clone the array for naming usage
$return = array(); // the array returned for testing purposes
$j = 0;
foreach($array as $num => $file){ // loop in the elements
if($file != $id){ // check if the current file is not the element we want to remove
if($num == $j){ // if current element and '$j' are the same we do not need to rename that file
$return[] = "// #rename('".$file."', '".$file."'); -- do not rename";
} else { // if previously we have removed the file '$id' then '$j' should be -1 and we rename the file with the next one stored in '$clone' array
$return[] = "#rename('".$file."', '".$clone[($num-1)]."'); // rename";
}
} else { // this is for the file we need to remove, we also -1 current '$j'
$j--;
}
$j++;
}
return $return;
}
print_r(removeElement($files, 'file5.jpg'));
it seems rudimentary, but it works and is easy to read.
$filecount = 5;
$i = 2;
unlink('photo/'. $i . '.jpg');
for($i; $i < $filecount; $i++) {
rename('photo/'. ($i+1) .'.jpg', 'photo/'. $i . '.jpg');
}
die;