[php] PHP import magento2
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- <?php
- use Magento\Framework\App\Bootstrap;
- error_reporting(E_ALL);
- ini_set("display_errors", 1);
- require __DIR__ . '/../app/bootstrap.php';
- if (! isset($_POST))
- exit();
- $params = $_SERVER;
- $bootstrap = Bootstrap::create(BP, $params);
- $objectManager = $bootstrap->getObjectManager();
- $state = $objectManager->get('Magento\Framework\App\State');
- $state->setAreaCode('frontend');
- $context = $objectManager->get('\Magento\Framework\App\Helper\Context');
- $attributeRepository = $objectManager->get('\Magento\Catalog\Api\ProductAttributeRepositoryInterface');
- $tableFactory = $objectManager->get('\Magento\Eav\Model\Entity\Attribute\Source\TableFactory');
- $attributeOptionManagement = $objectManager->get('\Magento\Eav\Api\AttributeOptionManagementInterface');
- $optionLabelFactory = $objectManager->get('\Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory');
- $optionFactory = $objectManager->get('\Magento\Eav\Api\Data\AttributeOptionInterfaceFactory');
- $registry = $objectManager->get('\Magento\Framework\Registry');
- $registry->register('isSecureArea', true);
- $productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
- $associatedIdMap = new stdClass();
- $nameSkuMap = new stdClass();
- $attributGustoMap = new stdClass();
- $attributeValues;
- function getAttribute($attributeCode)
- {
- global $attributeRepository;
- return $attributeRepository->get($attributeCode);
- }
- function createOrGetId($attributeCode, $label)
- {
- if (strlen($label) < 1) {
- throw new \Magento\Framework\Exception\LocalizedException(__('Label for %1 must not be empty.', $attributeCode));
- }
- global $attributGustoMap;
- global $optionLabelFactory;
- global $optionFactory;
- global $attributeOptionManagement;
- // Does it already exist?
- $optionId = getOptionId($attributeCode, $label);
- if (! $optionId) {
- // If no, add it.
- $optionLabel = $optionLabelFactory->create();
- $optionLabel->setStoreId(0);
- $optionLabel->setLabel($label);
- $option = $optionFactory->create();
- $option->setLabel($label);
- $option->setStoreLabels([
- $optionLabel
- ]);
- $option->setSortOrder(0);
- $option->setIsDefault(false);
- $attrId = getAttribute($attributeCode)->getAttributeId();
- $attributeOptionManagement->add(\Magento\Catalog\Model\Product::ENTITY, '157', $option);
- // Get the inserted ID. Should be returned from the installer, but it isn't.
- $optionId = getOptionId($attributeCode, $label, true);
- $attributGustoMap->$label = $optionId;
- }
- return $optionId;
- }
- function getOptionId($attributeCode, $label, $force = false)
- {
- global $attributGustoMap, $attributeValues;
- if (property_exists($attributGustoMap, $label)) {
- return $attributGustoMap->$label;
- }
- $attribute = getAttribute($attributeCode);
- global $tableFactory;
- // Build option array if necessary
- if ($force === true || ! isset($attributeValues[$attribute->getAttributeId()])) {
- $attributeValues[$attribute->getAttributeId()] = [];
- // We have to generate a new sourceModel instance each time through to prevent it from
- // referencing its _options cache. No other way to get it to pick up newly-added values.
- $sourceModel = $tableFactory->create();
- $sourceModel->setAttribute($attribute);
- foreach ($sourceModel->getAllOptions() as $option) {
- $attributeValues[$attribute->getAttributeId()][$option['label']] = $option['value'];
- }
- }
- // Return option ID if exists
- if (isset($attributeValues[$attribute->getAttributeId()][$label])) {
- return $attributeValues[$attribute->getAttributeId()][$label];
- }
- // Return false if does not exist
- return false;
- }
- $name = $_FILES['file']['name'];
- $temp_name = $_FILES['file']['tmp_name'];
- if (isset($name) and ! empty($name)) {
- $location = './';
- if (move_uploaded_file($temp_name, $location . $name)) {
- $xml = simplexml_load_file($name, null, LIBXML_PARSEHUGE | LIBXML_NOWARNING);
- $deletedProductList = $xml->DeletedProducts->Product;
- $updateProductsList = $xml->UpdatedProducts->Product;
- $product;
- if (is_object($updateProductsList)) {
- for ($i = 0; $i < count($updateProductsList); $i ++) {
- $desc = $updateProductsList[$i]->Description;
- $code = (string) $updateProductsList[$i]->Code;
- $price = (float) $updateProductsList[$i]->GrossPrice1;
- $brand = (string) $updateProductsList[$i]->ProducerName;
- $qty = (int) $updateProductsList[$i]->AvailableQty;
- try {
- $product = $productRepository->get($code);
- } catch (Exception $e) {
- $product = $objectManager->create('Magento\Catalog\Model\Product');
- }
- $product->setSku($code);
- $product->setPrice($price);
- $product->setStockData(array(
- 'use_config_manage_stock' => 0, // 'Use config settings' checkbox
- 'manage_stock' => 1, // manage stock
- 'is_in_stock' => 1, // Stock Availability
- 'qty' => $qty // qty
- ));
- $notes = (string) $updateProductsList[$i]->Notes;
- $scadenza = false;
- if (str_contains($notes, "--scadenza:")) {
- $scadenza = explode("--scadenza:", $notes)[1];
- $scadenza = trim($scadenza);
- $scadenzaArray = explode("/", $scadenza);
- if (count($scadenzaArray) == 3) {
- $scadenza = $scadenzaArray[1] . '/' . $scadenzaArray[0] . '/' . $scadenzaArray[2];
- $product->setCustomAttribute('scadenza', $scadenza);
- }
- }
- //BRANDO MIO
- $existsbrand = GetBrandIdFromName($brand);
- if(!$existsbrand) {
- $brid = createBrand($brand);
- } else {
- $brid = $existsbrand;
- }
- if($hasbrand = HasBrand($product->getId())) {
- $newbr = UpdateProdBrand($product->getId(), $brid);
- }
- else {
- $newbr = NewProdBrand($product->getId(), $brid);
- }
- /////////
- if (! str_contains($desc, '--')) {
- // simple
- $product->setName($desc);
- upsertProduct($product, 'simple');
- } else {
- $prodName = explode('--', $desc)[0];
- if (str_contains($desc, 'BASE')) {
- // configurable
- $product->setName($prodName);
- $product = upsertProduct($product, 'configurable');
- $nameSkuMap->$prodName = $code;
- } else if (str_contains($desc, 'gusto:')) {
- // associated
- $product->setName($prodName);
- $gustoAttrCode = $product->getResource()
- ->getAttribute("gusto")
- ->getAttributeCode();
- $gustoId = createOrGetId($gustoAttrCode, trim(strtolower(explode('--gusto:', $desc)[1])));
- $product->setGusto($gustoId);
- $product = upsertProduct($product, 'simple', 1);
- $productId = $product->getId();
- if (property_exists($associatedIdMap, $prodName)) {
- $associatedIdArray = $associatedIdMap->$prodName;
- array_push($associatedIdArray, $productId);
- } else {
- $associatedIdArray = array(
- $productId
- );
- }
- $associatedIdMap->$prodName = $associatedIdArray;
- } else {
- echo "unknown product type - " . $code . "\n";
- // unknown
- }
- }
- }
- }
- foreach ($associatedIdMap as $productName => $prodAssocIds) {
- if (property_exists($nameSkuMap, $productName)) {
- updateAssociatedIds($nameSkuMap->$productName, $prodAssocIds);
- } else {
- echo "no base product - " . $productName . "\n";
- }
- }
- if (is_object($deletedProductList)) {
- for ($i = 0; $i < count($deletedProductList); $i ++) {
- $code = $deletedProductList[$i]->Code;
- try {
- $product = $productRepository->get($code);
- $productRepository->delete($product);
- } catch (Exception $e) {
- echo "Cannot Delete - sku not exists - " . $code . "\n";
- }
- }
- }
- echo "OK";
- } else {
- echo 'not uploaded';
- }
- } else {
- echo 'You should select a file to upload !!';
- }
- ////////////////////////////
- function updateAssociatedIds($code, $productIds)
- {
- global $productRepository;
- $product = $productRepository->get($code);
- $product_resource = $product->getResource();
- $gusto_attribute = $product_resource->getAttribute('gusto');
- $gusto_attribute_id = $gusto_attribute->getId();
- $configurable_attributes = array(
- 'gusto'
- );
- $product->getTypeInstance()->setUsedProductAttributeIds(array(
- $gusto_attribute_id
- ), $product);
- $configurable_attributes_data = $product->getTypeInstance()->getConfigurableAttributesAsArray($product);
- $product->setCanSaveConfigurableAttributes(true);
- $product->setConfigurableAttributesData($configurable_attributes_data);
- $product->setAssociatedProductIds($productIds);
- $product->save();
- }
- ////////////////////////////
- function upsertProduct($product, $type, $visibility = 4)
- {
- $product->setTypeId($type)
- ->setStatus(1)
- ->
- // 1 = enabled, 2 = disabled
- setAttributeSetId(4)
- ->
- // 4 = default
- setTaxClassId(2)
- ->
- // 0 = None, 2 = Default product tax class
- setCategoryIds(array(
- 2
- ))
- ->
- // 2 = Default category
- setWebsiteIds(array(
- 1
- ))
- ->
- // 1 = Default Website ID
- setStoreId(0)
- ->setUrlKey($product->getSku())
- ->
- // 0 = Default store ID
- setVisibility($visibility); // 4 = Catalog & Search
- $product->save();
- return $product;
- }
- //////////////////
- function GetBrandIdFromName($brname) {
- $conn = new mysqli($servername, $username, $password);
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $stmt = $conn->prepare("SELECT brand_id FROM magento.tm_brand WHERE name = ?");
- $param = "$brname";
- $stmt->bind_param("s", $param);
- $stmt->execute();
- $stmt->store_result();
- $stmt->bind_result($brid);
- $rez = null;
- while($stmt->fetch()){
- $rez = $brid;
- }
- $stmt->close();
- $conn->close();
- return $rez;
- }
- //////////////////
- function createBrand($brname) {
- $urlkey = str_replace(" ", "-", $brname);
- $urlkey = str_replace("\"", "", $urlkey);
- $urlkey = str_replace("'", "", $urlkey);
- $urlkey = strtolower($urlkey);
- $conn = new mysqli($servername, $username, $password);
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $stmt = $conn->prepare("INSERT INTO magento.tm_brand (name, status, url_key, title, website_id) VALUES (?, 1, ?, ?, 1)");
- $stmt->bind_param("sss", $brname, $urlkey, $brname);
- $stmt->execute();
- $rinsid = $stmt->insert_id;
- $stmt->close();
- $conn->close();
- return $rinsid;
- }
- //////////////////
- function HasBrand($prid) {
- $conn = new mysqli($servername, $username, $password);
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $stmt = $conn->prepare("SELECT value FROM magento.catalog_product_entity_int where attribute_id = 150 AND entity_id = ?");
- $stmt->bind_param("i", $prid);
- $stmt->execute();
- $stmt->store_result();
- $stmt->bind_result($bid);
- $rez = null;
- while($stmt->fetch()){
- $rez = $bid;
- }
- $stmt->close();
- $conn->close();
- return $rez;
- }
- //////////////////////////
- function UpdateProdBrand($prid, $brid) {
- $conn = new mysqli($servername, $username, $password);
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $stmt = $conn->prepare("UPDATE magento.catalog_product_entity_int SET value = ? WHERE entity_id = ?; ");
- $stmt->bind_param("ii", $brid, $prid);
- $stmt->execute();
- $rr = $stmt->affected_rows;
- $stmt->close();
- $conn->close();
- return $rr;
- }
- ////////////////////////////
- function NewProdBrand($prid, $brid) {
- $conn = new mysqli($servername, $username, $password);
- if ($conn->connect_error) {
- die("Connection failed: " . $conn->connect_error);
- }
- $stmt = $conn->prepare("INSERT INTO magento.catalog_product_entity_int (attribute_id, store_id, entity_id, value) VALUES (150, 0, ?, ?); ");
- $stmt->bind_param("ii", $prid, $brid);
- $stmt->execute();
- $rr = $stmt->affected_rows;
- $stmt->close();
- $conn->close();
- return $rr;
- }
Editor
You can edit this paste and save as new:
File Description
- PHP import magento2
- Paste Code
- 19 Jul-2021
- 13.8 Kb
You can Share it:
Latest Code Pastes