ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 以编程方式运行Magento 1.9.1.0 Dataflow导入配置文件

2019-05-19 20:15:58  阅读:277  来源: 互联网

标签:php import xml magento dataflow


我试图让这个工作,但似乎找不到解决方案.我正在寻找运行ID = 3的现有数据流配置文件,并且已经配置了导入文件名.

我所做的所有研究都会导致以下代码的一些变化:

public function importProducts($profile_id = 3)
{

    require_once('../app/Mage.php');

    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

    // Instantiate a session for the "root" user.
    $userModel = Mage::getModel('admin/user');
    $userModel->setUserId(0);
    Mage::getSingleton('admin/session')->setUser($userModel);

    // Load the dataflow profile.
    $profile = Mage::getModel('dataflow/profile');
    $profile->load($profile_id);
    if (!$profile->getId()) {
        exit("Profile with id #{$profile_id} does not exist.");
    }

    $profile->run();

    $batchModel = Mage::getSingleton('dataflow/batch');

    // Reporting.
    $direction = ucwords($profile->getDirection());
    $success = "{$direction} with id #{$batchModel->getId()} completed succesfully.\n";

    echo $success;

    return true;
}

从Magento后端运行有问题的配置文件(ID = 3)可以很好地工作,似乎无法从上面的PHP函数中触发它.

我正在寻找一种以编程方式触发“导入所有产品”数据流配置文件的方法.

我遇到的其他帖子,问题和网站却没有成功:

> http://phpmysqltalk.com/1718-magento-dataflow-exportimport-form-the-command-line.html
> https://www.variux.com/magento-1-8-ce-importexport-from-shell-on-bitnami/
> Run multiple Magento DataFlow profiles in sequence
> https://gist.github.com/ameenross/91b85beb45f1ff0a23c6

任何和所有的帮助将不胜感激!

谢谢!

解决方法:

经过多次挫折之后,这里的答案是有效的:

请注意,在这种情况下,我已经为导入所有产品(ID:3)配置了默认的Magento数据流配置文件,以便从预定义的文件中读取XML导入格式.这是我在运行导入操作之前根据需要创建的文件. (请参阅上面问题中的屏幕截图)

创建个人资料后,您需要2个文件:

> importer.php
> batch_importer_processor.php

您可以将文件放在/ magento / root / shell /目录中,或者如果要包含在单独的位置,则根据需要调整路径.进入目录后,您可以通过cron调用触发操作:

    php -f /path/to/magento/root/directory/shell/importer.php

上面的-f参数是“解析并执行”被调用的文件.

每个文件的来源是:

importer.php

<?php         

    require_once '../app/Mage.php';

    set_time_limit(0);
    ini_set('memory_limit', '128M');

    $root       = "/path/to/your/magento/root/directory/";
    $logFile    = 'magento_import.log';

    umask(0);
    $app = Mage::app('default');

    Mage::log("========================== BEGIN IMPORT ==========================", null, $logFile);
    //echo "========================== BEGIN IMPORT ==========================\n";

    // Login Admin User

    Mage::getSingleton('core/session', array('name' => 'adminhtml'));

    $user = Mage::getModel('admin/user')->loadByUsername($username);

    if (Mage::getSingleton('adminhtml/url')->useSecretKey()) {
      Mage::getSingleton('adminhtml/url')->renewSecretUrls();
    }

    $session = Mage::getSingleton('admin/session');
    $session->setIsFirstVisit(true);
    $session->setUser($user);
    $session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
    Mage::dispatchEvent('admin_session_user_login_success',array('user'=>$user));

    if ($session->isLoggedIn()) {

        Mage::log("User '" . $username . "' logged in.", null, $logFile);
        //echo "User '" . $username . "' logged in.\n";

    } else {

        Mage::log("ERROR: Could not login as user '" . $username . "'.", null, $logFile);
        //echo "ERROR: Could not login as user '" . $username . "'.\n";

    }

    // Load DataFlow Profile

    $profile_id = 3;

    $profile = Mage::getModel('dataflow/profile');

    $profile->load($profile_id);

    if (!$profile->getId()) {

        Mage::log("ERROR: Profile with ID #{$profile_id} does not exist.", null, $logFile);
        //echo "ERROR: Profile with ID #{$profile_id} does not exist.\n";
        exit;

    }

    Mage::register('current_convert_profile', $profile);

    $profile->run();

    // Begin Bactch Processing

    // Limit of products per batch (max: 50)
    $batchLimit = 50;

    function convert($size)
    {

        $unit=array('b','kb','mb','gb','tb','pb');

        return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];

    }

    $batchModel = Mage::getSingleton('dataflow/batch');

    if (!$batchModel->getId()) {

        Mage::log(convert(memory_get_usage()) . " - ERROR: Can't get batchModel", null, $logFile);
        //echo convert(memory_get_usage()) . " - ERROR: Can't get batchModel\n";
        exit;

    }

    if (!$batchModel->getAdapter()) {

        Mage::log(convert(memory_get_usage()) . " - ERROR: Can't getAdapter", null, $logFile);
        //echo convert(memory_get_usage()) . " - ERROR: Can't getAdapter\n";
        exit;

    }

    $batchId            = $batchModel->getId();
    $batchImportModel   = $batchModel->getBatchImportModel();
    $importIds          = $batchImportModel->getIdCollection();

    $recordCount        = null;
    $totalproducts      = count($importIds);

    $saved              = 0;
    $batchArrayIds      = array();

    foreach ($importIds as $importId) {

        $recordCount++;

        $batchArrayIds[] = $importId;

        if ($recordCount%$batchLimit == 0 || $recordCount == $totalproducts) {

            $paramsArr  = array('batchid' => $batchId, 'ids' => $batchArrayIds);
            $params     = json_encode($paramsArr);
            $result     = array();

            exec("php -f {$root}shell/batch_import_processor.php '{$params}'", $result);

            $saved += $result[0];

            Mage::log(convert(memory_get_usage()) . " - processed {$recordCount}/$totalproducts. Saved {$result[0]} products.", null, $logFile);
            //echo convert(memory_get_usage()) . " - processed {$recordCount}/$totalproducts. Saved {$result[0]} products.\n";

            $batchArrayIds = array();

        }

    }


    $batchModel = Mage::getModel('dataflow/batch')->load($batchId);

    try {

        $batchModel->beforeFinish();

    } catch (Mage_Core_Exception $e) {

        Mage::log(convert(memory_get_usage()) . " - ERROR: ". $e->getMessage(), null, $logFile);
        //echo convert(memory_get_usage()) . " - ERROR: ". $e->getMessage() . "\n";

    } catch (Exception $e) {

        Mage::log(convert(memory_get_usage()) . " - ERROR: An error occurred while finishing process. Please refresh the cache" . $e->getMessage(), null, $logFile);
        //echo convert(memory_get_usage()) . " - ERROR: An error occurred while finishing process. Please refresh the cache" . $e->getMessage() . "\n";

    }

    $batchModel->delete();

    // Output Debugging Info
    foreach ($profile->getExceptions() as $e) {

        Mage::log(convert(memory_get_usage()) . " - " . $e->getMessage(), null, $logFile);
        //echo convert(memory_get_usage()) . " - " . $e->getMessage() . "\n";

    }

    Mage::log("IMPORT COMPLETE.", null, $logFile);
    //echo "IMPORT COMPLETE.\n";

?>

batch_import_processor.php

<?php

    $root       = '/your/path/to/magento/root/directory/';
    $logFile    = 'magento_import.log';

    require_once $root . 'app/Mage.php';

    set_time_limit(0);
    ini_set('memory_limit', '128M');

    ob_implicit_flush();

    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

    $params             = $argv[1];
    $paramsArray        = json_decode($params, true);
    $batchId            = $paramsArray['batchid'];
    $importIds          = $paramsArray['ids'];

    $saved              = 0;
    $batchModel         = Mage::getModel('dataflow/batch')->load($batchId);
    $batchImportModel   = $batchModel->getBatchImportModel();
    $adapter            = Mage::getModel($batchModel->getAdapter());

    $adapter->setBatchParams($batchModel->getParams());

    foreach ($importIds as $importId) { 

        $batchImportModel->load($importId);

        if (!$batchImportModel->getId()) {

            Mage::log(convert(memory_get_usage()) . " - ERROR: Skip undefined row {$importId}", null, $logFile);
            //echo convert(memory_get_usage()) . " - ERROR: Skip undefined row {$importId}\n";
            continue;

        }

        try {

            $importData = $batchImportModel->getBatchData();
            $adapter->saveRow($importData);

        } catch (Exception $e) {

            Mage::log("Exception : " . $e, null, $logFile);
            //echo "Exception : " . $e;
            continue;

        }

        $saved ++;

    }

    if (method_exists($adapter, 'getEventPrefix')) {

        // Event to process rules relationships after import
        Mage::dispatchEvent($adapter->getEventPrefix() . '_finish_before', array(
        'adapter' => $adapter
        ));

        // Clear affected ids for possible reuse
        $adapter->clearAffectedEntityIds();

    }

    Mage::log("Total Products to Import: " . $saved, null, $logFile);
    echo $saved;

?>

添加到此代码并不困难,因此如果您需要,可以按顺序运行多个配置文件.否则,请务必从Magento后端获取配置文件ID,并将$profile_id变量设置为所需的值.

如果您更喜欢这条路线,我已经包含了对Magento Log(Mage :: log)的调用以及下面各自的echo语句.根据需要编辑.日志应保存在/ magento / root / var / log /目录中.请务必通过以下方式在Magento后端启用此功能:

>系统>配置>高级>开发人员>日志设置

设置启用为“是”,请参阅以下内容:

 

运行importer.php文件后,/ magento / root / var / log /目录中应该有2个日志文件:

> system.log
> magento_import.log

您可能还拥有始终启用的exception.log文件.

这是我发现与Magento 1.9.1.0合作的唯一解决方案,感谢Andrey的灵感.

任何想法或改进都是受欢迎的.

标签:php,import,xml,magento,dataflow
来源: https://codeday.me/bug/20190519/1137287.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有