我得到了ascript,它帮助我将一些数据添加到csv文件中,基于图像是否在文件夹内(退出与否)的事实。文件是图像,所以我需要检查文件是否存在,以及是否是png,jpg,jpeg,gif。
到目前为止它只检查它是否是JPG但我希望它找到文件存在,如果它是PNG或JPEG甚至GIF。
<?php
$columns = array("row1","row2","row3","row4","row5","row6","row7","row8","row9",
"row10","row11","row12","row13","row14","row15","row16","row17","row18"
);
$rootDir = "/path/to/images/folder/files";
$file = fopen("database.csv", "r") or die('fopen database failed');
$newFile = fopen("newdata.csv", "w") or die('fopen newdata.csv failed');
while (($data = fgetcsv($file, 999999, ";")) !== FALSE) {
$row = array_combine($columns, $data);
$filename = $row['row4'].".jpg"; // could be png or jpEg, or even gif
if (file_exists("$rootDir/$filename")) {
$row['image'] = .$filename; //also needs correct extension of image which exists.
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
}
fputcsv($newFile, array_values($row), ";",'"' );
}
fclose($file);
fclose($newFile);
?>
答案 0 :(得分:0)
您可以这样做:
<击> 撞击>
<击>// your code
$possible_extensions = array("jpg", "jpeg", "png", "gif");
$row = array_combine($columns, $data);
foreach($possible_extensions as $ext){
$filename = $row['row4'] . "." . $ext;
if (file_exists("$rootDir/$filename")) {
$row['image'] = .$filename;
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
break;
}
}
fputcsv($newFile, array_values($row), ";",'"' );
// your code
击> <击> 撞击>
<强>编辑:强>
如果您想执行不区分大小写的file_exists()
检查,那么这就是解决方案,
以下fileExists()
函数返回完整路径文件(如果找到),false
(如果没有)。
function fileExists($fileName, $caseSensitive = true) {
if(file_exists($fileName)) {
return $fileName;
}
if($caseSensitive) return false;
// Handle case insensitive requests
$directoryName = dirname($fileName);
$fileArray = glob($directoryName . '/*', GLOB_NOSORT);
$fileNameLowerCase = strtolower($fileName);
foreach($fileArray as $file) {
if(strtolower($file) == $fileNameLowerCase) {
return $file;
}
}
return false;
}
这是来源:
现在你的代码,
// your code
$possible_extensions = array("jpg", "jpeg", "png", "gif");
$row = array_combine($columns, $data);
foreach($possible_extensions as $ext){
$filename = $row['row4'] . "." . $ext;
if ($filename = fileExists("$rootDir/$filename", false)) {
$row['image'] = .$filename; //also needs correct extension of image which exists.
$row['small_image'] = .$filename;
$row['thumbnail'] = .$filename;
break;
}
}
fputcsv($newFile, array_values($row), ";",'"' );
// your code