问题
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);
?>
回答1:
This should work.
$oldname = "$dir"."$names[1] $names[2]".".txt";
$newname = "$dir"."$names[0]".".txt";
回答2:
- Make sure
$dir
is set properly. Run is_dir() on it to make sure you've got it. - In your code,
$oldname
and$newname
end with .txt, but you described them as .jpg in your description. - Try clearing your stat cache at the beginning of your script.
回答3:
- You have to have $dir followed with the directory separator ( / or \ ).
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.
来源:https://stackoverflow.com/questions/5114310/php-rename-files-from-csv