PHP rename files from CSV

2019-08-15 04:41发布

I am working on some PHP to rename photos in a directory to something else based on data from a CSV file. The CSV has three columns: Number, FirstName and LastName. The original names of the photos are "FirstName LastName.jpg". The new names should be "Number.jpg". I do this by cycling through the lines of the CSV, making the old name by putting FirstName and LastName together, making the new name by getting the number and renaming the files. However, I have two problems:

The first is more of a bug, but it might be significant. When I echo $oldname, there is a line break between the name and the dot before the extension, even though I have specified it as one string with no breaks.

The second is that it never works. It always returns "DID NOT rename whatever". I have changed the permissions of the files and containing folder but it still doesn't work. Thanks in advance if you can help.

<?php
$dir = "*Dir to phptos*";
$csv = fopen("filename.csv", "r") or die("no csv file");
//$ext = ".txt";

while(!feof($csv)) {
$line = fgets($csv);
$names = explode(",", $line);

//echo $names[2];

$oldname = $dir.$names[1]." ".$names[2].".txt";
$newname = $dir.$names[0].".txt";

if (is_file($oldname)) {
rename($oldname, $newname);

echo "renamed '".$oldname."' to '".$newname."'<br/>";
} else {
echo "DID NOT rename '".$oldname."'<br/>\n";
//echo "$oldname";
}
}

fclose($csv);
?>

3条回答
等我变得足够好
2楼-- · 2019-08-15 04:53

This should work.

$oldname = "$dir"."$names[1] $names[2]".".txt";
$newname = "$dir"."$names[0]".".txt";
查看更多
闹够了就滚
3楼-- · 2019-08-15 04:58
  1. Make sure $dir is set properly. Run is_dir() on it to make sure you've got it.
  2. In your code, $oldname and $newname end with .txt, but you described them as .jpg in your description.
  3. Try clearing your stat cache at the beginning of your script.
查看更多
姐就是有狂的资本
4楼-- · 2019-08-15 05:14
  1. You have to have $dir followed with the directory separator ( / or \ ).
  2. You getting the line break because the line break in the CSV standard is equal to \r\n while the line break in php usually equals to \n (if the auto_detect_line_endings directive not set). In this case you're receiving \r in your strings. You have to trim() (http://php.net/manual/en/function.trim.php) or

    preg_replace('/\s*/', '\ ', $line); // space is the value of the second parameter

all the data parsed. You'll be able to rename files after getting rid of the special chars from your filenames.

查看更多
登录 后发表回答