我有一个csv文件,它有14列和数百行。有一个标题是"sku","category","description","brand"
等
所有的数据都准备好了,但我正试图在CSV中的一些特定列( "images", "small_image" , "thumnail" ).
中添加一些图像文件名
标题看起来像这样:
+-----+----------+-------------+-------+-------------+-----------+--------+------+
| sku | category | description | image | small_image | thumbnail | price | color|
+-----+----------+-------------+-------+-------------+-----------+--------+------+
所以知道标题是什么样子的,那么第一行应该是:
+-------+---------------+------------------+---+---+----+-----+--------+
| sku01 | category name | description here | | | | 99$ | black |
+-------+---------------+------------------+---+---+----+-----+--------+
jpeg的文件名与同一行的sku
值相同,扩展名为jpeg。例如,如果第一行的sku
列有sku01
,那么同一行的图像列中的文件名将是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"];
然后,您需要打开文件并对其进行迭代,构建一个键值对的关联数组,检查是否存在该图像名称的文件,如果存在,则为数组指定正确的名称。
$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);
现在,您有了插入了新值的原始文件的副本。