Magento2根据图片文件包导入产品图片

图片包给的图片文件是子产品的图片,如下图:A104255是主产品的sku

php 复制代码
<?php

/**
 * 根据图片包导入产品图片,包含子产品和主产品
 * 子产品是作为主图,主产品是作为附加图片
 */

use Magento\Framework\App\Bootstrap;

include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\ResourceConnection $resource */
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');

$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');

/** @var  \Magento\Catalog\Model\ProductFactory $productFactory */
$productFactory = $objectManager->create('\Magento\Catalog\Model\ProductFactory');

/** @var  \Magento\Catalog\Model\ResourceModel\MediaImageDeleteProcessor $mediaImageDeleteProcessor */
$mediaImageDeleteProcessor = $objectManager->create('\Magento\Catalog\Model\ResourceModel\MediaImageDeleteProcessor');

$imageFolder = $directory->getRoot().'/pub/media/images_import';
$delUrl = $directory->getRoot().'/pub/media/catalog/product';

$existsSku = [];

try {
    // 指定搜索的文件夹和文件名进行搜索
    $folder = $imageFolder;
    //$fileName = $sku;
    $fileName = '*.jpg';

    // 执行搜索并获取结果数组
    $imgfiles = searchImagesInFolder($folder, $fileName);
    //print_r($imgfiles);die;

    if ($imgfiles) {
        foreach ($imgfiles as $imgfile) {
            try {
                $mainImagePath = $imgfile;
                if(is_file($mainImagePath)){
                    $pathArr = explode('/', $mainImagePath);
                    $imgName = end($pathArr);

                    $sku = explode('.', $imgName)[0];
                    if (in_array($sku, $existsSku)) continue;
                    //if ($sku != 'B302170-5g') continue;

                    //var_dump($sku);die;

                    $sql = $connection->select()->from('catalog_product_entity')
                        ->where('sku = ?', $sku);
                    $row = $connection->fetchRow($sql);
                    if (!$row) {
                        echo $sku,' 不存在',PHP_EOL;
                        continue;
                    }

                    $product = $productFactory->create()->loadByAttribute('sku',$sku);
                    $rowId = $product->getRowId();

                    if (strstr($sku, '-')){ #主图
                        #删除原有的图片
                        /*$del = $connection->fetchAll("SELECT * from catalog_product_entity_media_gallery where value_id in( select value_id from catalog_product_entity_media_gallery_value_to_entity where row_id='{$rowId}')");
                        foreach ($del as $key=>$value){
                            if (file_exists($delUrl.'/'.$value['value'])) {
                                unlink($delUrl . '/' . $value['value']);
                            }
                        }

                        # 删除产品和图片的关联关系
                        $connection->query("delete from catalog_product_entity_media_gallery where value_id in( select value_id from catalog_product_entity_media_gallery_value_to_entity where row_id='{$rowId}')");
                        $connection->query("delete from catalog_product_entity_media_gallery_value_to_entity where row_id='{$rowId}'");
                        $connection->query("delete from catalog_product_entity_varchar where row_id='{$rowId}' and attribute_id in(87,88,89)");*/

                        echo $sku,' 主图',PHP_EOL;
                        $product->setStoreId(0)->addImageToMediaGallery($mainImagePath, array('image', 'small_image', 'thumbnail'), false, false);
                    }

                    $product->save();

                    #作为主产品的附加图
                    $sku_master = explode('-', $sku)[0] ?? '';
//                    var_dump($sku_master);die;

                    if (!$sku_master) continue;
                    if (in_array($sku_master, $existsSku)) continue;

                    $sql = $connection->select()->from('catalog_product_entity')
                        ->where('sku = ?', $sku_master);
                    $row = $connection->fetchRow($sql);
                    if (!$row) {
                        echo $sku_master,' 不存在',PHP_EOL;
                        continue;
                    }

                    $product_master = $productFactory->create()->loadByAttribute('sku',$sku_master);
                    $rowId = $product_master->getRowId();

                    #主产品导完删除图片
                    $product_master->setStoreId(0)->addImageToMediaGallery($mainImagePath, [], true, false);
                    $product_master->save();
                    echo $sku_master,' 子图',PHP_EOL;
                }else{
                    echo $sku." skip\n";
                }
            } catch (\Exception $e){
                throw new Exception($e->getMessage());
            }
        }
    } else {
        echo "没有找到匹配的文件。",PHP_EOL;
    }

} catch (\Exception $e){
    echo $e->getMessage(),PHP_EOL;
}
//    }
//}

function searchImagesInFolder($folder, $fileName)
{
    // 检查文件夹是否存在
    if (!is_dir($folder)) {
        return [];
    }

    // 初始化结果数组
    $result = [];

    // 打开文件夹
    $handle = opendir($folder);

    // 遍历文件夹中的文件和子文件夹
    while (($file = readdir($handle)) !== false) {
        if ($file != '.' && $file != '..') {
            $path = $folder . DIRECTORY_SEPARATOR . $file;

            // 如果是文件夹,则递归调用自身进行进一步搜索
            if (is_dir($path)) {
                $result = array_merge($result, searchImagesInFolder($path, $fileName));
            } else {
                // 如果是图片文件并且文件名与模糊匹配成功,则将文件路径添加到结果数组中
                if (isImageFile($file) && fnmatch("*{$fileName}*", $file)) {
                    $result[] = $path;
                }
            }
        }
    }

    // 关闭文件夹
    closedir($handle);

    return $result;
}

// 检查文件是否为图片文件
function isImageFile($file)
{
    $imageExtensions = ["jpg", "jpeg", "png", "gif"];
    $fileExtension = pathinfo($file, PATHINFO_EXTENSION);
    return in_array($fileExtension, $imageExtensions);
}
相关推荐
AI+程序员在路上17 小时前
网桥及IP转发在嵌入式linux eth0与wlan0连接使用方法
linux·tcp/ip·php
微爱帮监所写信寄信1 天前
微爱帮监狱寄信写信系统后台PHP框架优化实战手册
android·开发语言·人工智能·网络协议·微信·https·php
白帽子黑客罗哥1 天前
网络安全防护技术与实战策略:从基础防御到前沿应对
安全·web安全·php
快点好好学习吧1 天前
PHP程序员到底为什么要学习正则表达式?使用场景是什么?底层原理是什么?
学习·正则表达式·php
Smartdaili China1 天前
如何在桌面和移动设备上修复YouTube错误400
开发语言·php·error·youtube·移动·住宅ip·错误400
yyf198905251 天前
用PHP实现论坛功能
php
毕设源码-赖学姐1 天前
【开题答辩全过程】以 基于PHP的国学诗词网站与推荐系统的设计与实现为例,包含答辩的问题和答案
开发语言·php
oMcLin1 天前
如何在 Ubuntu 24.04 上安装 LAMP 堆栈(包括 PHP 8.3 和 MariaDB 11)
ubuntu·php·mariadb
运维闲章印时光1 天前
单位本部与分部网络已实现互联互通,网络访问通畅,数据传输正常
开发语言·网络·php
福尔摩斯张2 天前
Linux的pthread_self函数详解:多线程编程中的身份标识器(超详细)
linux·运维·服务器·网络·网络协议·tcp/ip·php