mlc*_*clm 1 php database csv fputcsv
我有一个csv文件,有14列,数百行.有一个标题"sku","category","description","brand"等.
所有数据都已存在,但我正在尝试在CSV中添加一些图像文件名,在某些特定列中 ( "images", "small_image" , "thumnail" ).
标题类型如下所示:
+-----+----------+-------------+-------+-------------+-----------+--------+------+
| sku | category | description | image | small_image | thumbnail | price | color|
+-----+----------+-------------+-------+-------------+-----------+--------+------+
Run Code Online (Sandbox Code Playgroud)
所以知道标题的样子,然后第一行就像:
+-------+---------------+------------------+---+---+----+-----+--------+
| sku01 | category name | description here | | | | 99$ | black |
+-------+---------------+------------------+---+---+----+-----+--------+
Run Code Online (Sandbox Code Playgroud)
jpeg的文件名sku与同一行的值相同,带有jpeg扩展名.因此,举例来说,如果sku01对sku第一行栏,文件名是sku01.jpeg在同一行中的图像列.那么small_image值和缩略图值也是如此.
但是,只有在jpeg存在于文件夹中时才会指定文件名.
到目前为止我知道如何使用fopen函数打开csv文件,最终将所有数据存储在一个数组中(我不知道这对我的情况是否有帮助),然后在检查file_exist之后是否在某些时候使用fputcsv函数在服务器上的特定文件夹中.
但是,对我而言,就我应该使用这些功能的顺序而言,我脑子里还是一团糟.我被卡住了.此外,我不知道如何将jpeg文件名放在右列(图像,缩略图,small_image),因为这些列位于csv文件的"中间",以及其他列.它们不在csv文件的末尾
我真的很感谢任何可以让我走上正确道路的人.
要执行您想要执行的操作,您应该首先将列拆分为与原始csv文件中显示的完全相同的数组:
$columns = ["sku","category","description","image","small_image","thumbnail", "price","color"];
Run Code Online (Sandbox Code Playgroud)
然后,您将要打开文件并对其进行迭代,构建键值对的关联数组,检查该图像名称是否存在文件,如果存在,则为数组指定正确的名称.
$rootDir = ""; //Root directory where your image files are located
$file = fopen("filehandle.csv", "r"); //Open the old file for reading
$newFile = fopen("newfilehandle.csv", "w"); //Create a new file for writing
while (($data = fgetcsv($file)) !== FALSE) {
$row = array_combine($columns, $data);
$filename = "{$row['sku']}.jpeg";
if (file_exists("$rootDir/$filename")) {
$row['image'] = $filename;
$row['small_image'] = $filename;
$row['thumbnail'] = $filename;
}
fputcsv($newFile, array_values($row)); //write data into new file
}
fclose($file);
fclose($newFile);
Run Code Online (Sandbox Code Playgroud)
现在,您已经插入了新值的原始文件的副本.