如何在 prestashop 程序化产品导入期间添加图像?

How to add image during programmatic product import in prestashop?

我找不到有关在产品插入期间添加图像的适当文档。这是我的 xml 产品导入脚本的工作代码。我不知道如何在添加产品的同时添加产品图片。

foreach ($xml->Products as $product_xml)
{
    if ($product_xml->Valid_internet_product == 1)
    {
        /* Update an existing product or Create a new one */
        $id_product = (int)Db::getInstance()->getValue('SELECT id_product FROM '._DB_PREFIX_.'product WHERE reference = \''.pSQL($product_xml->Reference).'\'');
        $product = $id_product ? new Product((int)$id_product, true) : new Product();
        $product->reference = $product_xml->Reference;
        $product->price = (float)$product_xml->Price;
        $product->active = (int)$product_xml->Active_product;
        $product->weight = (float)$product_xml->Weight;
        $product->minimal_quantity = (int)$product_xml->MinOrderQty;
        $product->id_category_default = 2;
        $product->name = utf8_encode($product_xml->Products_name);
        $product->description = utf8_encode($product_xml->Description);
        $product->description_short = utf8_encode($product_xml->Short_Description);
        $product->link_rewrite = Tools::link_rewrite($product_xml->Products_name);
        $product->image_url = 'http://i.imgur.com/jLThaBj.jpg';
        if (!isset($product->date_add) || empty($product->date_add))
            $product->date_add = date('Y-m-d H:i:s');
        $product->date_upd = date('Y-m-d H:i:s');
        $id_product ? $product->updateCategories(array(2)) : $product->addToCategories(array(2));


        $product->save();

        echo 'Product <b>'.$product->name.'</b> '.($id_product ? 'updated' : 'created').'<br />';
    }
} 

您从哪里购买 $xml-> 产品?您没有使用网络服务吗?

Product image是product之类的另一个对象,首先你应该创建一个新的imagen,然后将这个image id添加到product。

这是通过以下方法实现的:

AdminImportControllerCore::copyImg()

您可以直接copy/paste,或者根据需要进行更改。

你可以和我一样看到这里。查看代码开始添加新图像的第 209 行。

https://github.com/xabikip/PrestaShopWebService/blob/master/examples/createProduct.php

使用 AdminImportControllerCore::copyImg() 函数确实是最好的,尽管您可能无法调用该函数,因为它是 protected.

你可以做到 public 但那是一种“肮脏”的做法。我更愿意看到人们使用这段代码

class MyAdminImportController extends AdminImportControllerCore {
    public static function copyImg($id_entity, $id_image = null, $url = '', $entity = 'products', $regenerate = true) {
        return parent::copyImg($id_entity, $id_image, $url, $entity, $regenerate);
    }
}