PHP从CSV重命名文件 [英] PHP rename files from CSV

查看:35
本文介绍了PHP从CSV重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些 PHP,以根据 CSV 文件中的数据将目录中的照片重命名为其他名称.CSV 包含三列:数字、名字和姓氏.照片的原始名称是FirstName LastName.jpg".新名称应为Number.jpg".我通过循环浏览 CSV 的行来做到这一点,通过将 FirstName 和 LastName 放在一起来创建旧名称,通过获取数字和重命名文件来创建新名称.但是,我有两个问题:

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:

第一个更像是一个错误,但它可能很重要.当我回显 $oldname 时,名称和扩展名前的点之间有一个换行符,即使我已将其指定为一个没有中断的字符串.

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);
?>

推荐答案

这应该可行.

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

这篇关于PHP从CSV重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆