markocupic/import_from_csv

从csv文本文件导入数据记录。Contao开源CMS的后端扩展

安装: 195

依赖项: 1

建议者: 0

安全: 0

星标: 4

关注者: 2

分支: 3

开放问题: 4

类型:contao-module

1.0.5 2017-03-12 19:31 UTC

This package is auto-updated.

Last update: 2024-09-22 22:55:52 UTC


README

Contao 3后端模块

使用此模块可以一次性通过csv文件大量导入数据记录。当需要生成大量用户或成员时非常实用。csv文件最好在电子表格程序(如Excel)中创建,然后保存为逗号分隔的文件(csv)。该文件的示例位于import_from_csv/csv/example_csv.csv目录中。

警告!

注意!此模块非常有用。但是,用户应该了解自己在做什么,因为如果使用不当,可能会损坏数据库表,导致Contao无法正常工作。

设置

选择导入数据的数据表(必填项)

选择要将数据记录写入的表。

选择导入过程中的字段(必填项)

数据库表中仅写入所选字段。通常最好在这里选择所有字段。

字段分隔符(必填项)

指定csv文件中字段内容之间由哪个字符分隔。

字段包含符(必填项)

检查csv文件中的字段内容是否由一个字符进一步包含。通常是双引号。=> "

导入模式(必填项)

确定是否将csv文件中的数据记录附加到目标表中,或者先清空目标表(旧表)。注意!如果没有备份,则无法恢复删除的数据记录。

选择文件(必填项)

最后选择要写入数据库的文件。提示:选择文件后,请先点击“保存”,您将获得预览。

通过钩子调整导入机制

使用安全的钩子可以绕过或调整验证。以下示例中,将根据街道、城市和国家代码自动通过GoogleMaps的Curl请求获取导入时的地理坐标。坐标随后存储在$ arrCustomValidation ['value']中,并在方法末尾作为方法返回值返回数组。还可以生成错误消息,例如无法获取地理坐标。这将导致跳过数据记录,并将其写入数据库。

要使用钩子,请创建以下目录和文件结构

system/modules/my_import_from_csv_hook/

    config/

        config.php

        autoload.php

        autoload.ini

    classes/

        MyValidateImportFromCsv.php

在config.php中写入以下内容

<?php

/**
 * HOOKS
 */
if (TL_MODE == 'BE' && \Input::get('do') == 'import_from_csv')
{
    $GLOBALS['TL_HOOKS']['importFromCsv'][] = array('MCupic\ImportFromCsv\ValidateImportFromCsv', 'addGeolocation');
}

在ValidateImportFromCsv.php中写入以下内容。在addGeolocation()方法中编写您的验证逻辑。该方法期望两个参数,并返回包含字段值、错误消息等的关联数组作为返回值。

<?php

/**
 * Contao Open Source CMS
 * Copyright (C) 2005-2014 Leo Feyer
 * @package import_from_csv
 * @author Marko Cupic 2014, extension sponsered by Rainer-Maria Fritsch - Fast-Doc UG, Berlin
 * @link https://github.com/markocupic/import_from_csv
 * @license https://gnu.ac.cn/licenses/lgpl-3.0.html LGPL
 */

/**
 * Run in a custom namespace, so the class can be replaced
 */
namespace MCupic\ImportFromCsv;

/**
 * Class ImportFromCsvHookExample
 * Copyright: 2014 Marko Cupic Sponsor der Erweiterung: Fast-Doc UG, Berlin
 * @author Marko Cupic <m.cupic@gmx.ch>
 * @package import_from_csv
 */
class ImportFromCsvHookExample extends \System
{

    /**
     * cURL error messages
     */
    public $curlErrorMsg = null;

    /**
     * @param $arrCustomValidation
     * @param null $objBackendModule
     * @return array
     */
    public function addGeolocation($arrCustomValidation, $objBackendModule = null)
    {
        /**
         * $arrCustomValidation = array(
         *
         * 'strTable'               => 'tablename',
         * 'arrDCA'                 => 'Datacontainer array (DCA) of the current field.',
         * 'fieldname'              => 'fieldname',
         * 'value'                  => 'value',
         * 'arrayLine'              => 'Contains the current line/dataset as associative array.',
         * 'line'                   => 'current line in the csv-spreadsheet',
         * 'objCsvFile'             => 'the Contao file object'
         * 'skipWidgetValidation'   => 'Skip widget-input-validation? (default is set to false)',
         * 'hasErrors'              => 'Should be set to true if custom validation fails. (default is set to false)',
         * 'errorMsg'               => 'Define a custom text message if custom validation fails.',
         * 'doNotSave'              => 'Set this item to true if you don't want to save the datarecord into the database. (default is set to false)',
         * );
         */

        // tl_member
        if ($arrCustomValidation['strTable'] == 'tl_member')
        {
            // Get geolocation from a given address
            if ($arrCustomValidation['fieldname'] == 'geolocation')
            {

                // Do custom validation and skip the Contao-Widget-Input-Validation
                $arrCustomValidation['skipWidgetValidation'] = true;

                $strStreet = $arrCustomValidation['arrayLine']['street'];
                $strCity = $arrCustomValidation['arrayLine']['city'];
                $strCountry = $arrCustomValidation['arrayLine']['country'];

                $strStreet = str_replace(' ', '+', $strStreet);
                $strCity = str_replace(' ', '+', $strCity);
                $strAddress = $strStreet . ',+' . $strCity . ',+' . $strCountry;

                // Get Position from GoogleMaps
                $arrPos = $this->curlGetCoordinates(sprintf('http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false', $strAddress));

                if (is_array($arrPos['results'][0]['geometry']))
                {
                    $latPos = $arrPos['results'][0]['geometry']['location']['lat'];
                    $lngPos = $arrPos['results'][0]['geometry']['location']['lng'];

                    // Save geolocation in $arrCustomValidation['value']
                    $arrCustomValidation['value'] = $latPos . ',' . $lngPos;
                }
                else
                {
                    // Error handling
                    if ($this->curlErrorMsg != '')
                    {
                        $arrCustomValidation['errorMsg'] = $this->curlErrorMsg;
                    }
                    else
                    {
                        $arrCustomValidation['errorMsg'] = sprintf("Setting geolocation for (%s) failed!", $strAddress);
                    }
                    $arrCustomValidation['hasErrors'] = true;
                    $arrCustomValidation['doNotSave'] = true;
                }
            }
        }

        return $arrCustomValidation;
    }


    /**
     * Curl helper method
     * @param $url
     * @return bool|mixed
     */
    public function curlGetCoordinates($url)
    {
        // is cURL installed on the webserver?
        if (!function_exists('curl_init'))
        {
            $this->curlErrorMsg = 'Sorry cURL is not installed on your webserver!';
            return false;
        }

        // Set a timout to avoid the OVER_QUERY_LIMIT
        usleep(25000);

        // Create a new cURL resource handle
        $ch = curl_init();

        // Set URL to download
        curl_setopt($ch, CURLOPT_URL, $url);

        // Should cURL return or print out the data? (true = return, false = print)
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Timeout in seconds
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        // Download the given URL, and return output
        $arrOutput = json_decode(curl_exec($ch), true);

        // Close the cURL resource, and free system resources
        curl_close($ch);

        return $arrOutput;
    }
}

为了使Contao知道如何找到该类,应在后端为新创建的模块启动Autoload-Creator。这将填充autoload文件所需代码。Et voilà!祝您玩得开心!!!