承接 onlyphp/codeigniter3-csvimporter 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

onlyphp/codeigniter3-csvimporter

Composer 安装命令:

composer require onlyphp/codeigniter3-csvimporter

包简介

A robust CSV importer library for CodeIgniter 3 with background processing support, progress tracking, and detailed statistics. Perfect for handling large CSV files without timeouts or memory issues.

README 文档

README

Latest Version Total Downloads License

A robust CSV importer library for CodeIgniter 3 with background processing support, progress tracking, and detailed statistics. Perfect for handling large CSV files without timeouts or memory issues.

⚠️ Warning

DO NOT USE THIS PACKAGE IN PRODUCTION

This package is under active development and may contain critical bugs. It is primarily intended for personal use and testing. The current version has not undergone rigorous testing and may be unstable.

✨ Features

  • 🚀 Background processing support with OS-specific optimizations
  • 📊 Real-time progress tracking
  • 📈 Detailed statistics (inserts/updates/errors)
  • ⚠️ Comprehensive error handling
  • 💻 Shared hosting compatible & Cross-platform compatible (Windows & Linux)
  • ⏰ No cron job required
  • 🛠️ Customizable processing logic
  • 🔄 Memory-efficient chunk processing
  • ⚡ Configurable processing parameters
  • 📝 Skip empty rows automatically
  • 🔍 Detailed error tracking
  • 🖥️ Smart CPU load management
  • 🔄 Automatic process recovery
  • 🛡️ Process locking mechanism

🔧 System Requirements

  • PHP 8.0 or higher
  • CodeIgniter 3.x
  • proc_open and proc_close PHP functions enabled
  • MySQL database
  • Write permissions for temporary directory
  • For Linux: mpstat command available for CPU monitoring
  • For Windows: wmic command available for CPU monitoring

📦 Installation

Install via Composer:

composer require onlyphp/codeigniter3-csvimporter

📝 Usage

Basic Usage

// Initialize the processor
$processor = new \OnlyPHP\CSVSimpleImporter\CSVImportProcessor();

// Set callback function for processing each row
$processor->setCallback(function($row, $rowIndex, $models) {
    try {
        // Process your row data here
        return [
            'code' => 200,
            'action' => 'create',
            'message' => 'Success'
        ];
    } catch (\Exception $e) {
        return [
            'code' => 500,
            'error' => $e->getMessage()
        ];
    }
});

// Start processing
$jobId = $processor->process('/path/to/your/file.csv');

Advanced Configuration

$processor = new \OnlyPHP\CSVSimpleImporter\CSVImportProcessor();

// Set user ID for file ownership
$processor->setFileBelongsTo(1);

// Set HTML element ID for frontend progress tracking
$processor->setDisplayHTMLId('progress-bar-1');

// Configure CSV processing parameters
$processor->setMemoryLimit('1G')
         ->setDelimiter(',')
         ->setEnclosure('"')
         ->setEscape('\\')
         ->setChunkSize(1000)
         ->setRecordUpdateInterval(250)
         ->setSkipHeader(true);

// Load specific models for processing
$processor->setCallbackModel(['User_model', 'Product_model']);

// Set callback with loaded models
$processor->setCallback(function($row, $rowIndex, $models) {
    $userModel = $models['User_model'];
    $productModel = $models['Product_model'];

    try {
        // Your processing logic here
        $result = $userModel->createFromCSV($row);

        return [
            'code' => 200,
            'action' => 'create',
            'message' => 'User created successfully'
        ];
    } catch (\Exception $e) {
        return [
            'code' => 500,
            'error' => 'Row ' . $rowIndex . ': ' . $e->getMessage()
        ];
    }
});

// Start processing
$jobId = $processor->process('/path/to/your/encryptFileName.csv', 'originalFileName.csv');

Configuration Options

Method Description Default
setMemoryLimit() Set PHP memory limit for processing '1G'
setDelimiter() Set CSV delimiter character ','
setEnclosure() Set CSV enclosure character '"'
setEscape() Set CSV escape character '\'
setChunkSize() Set number of rows to process in each chunk 1000
setRecordUpdateInterval() Set database update interval (min 100) 200
setSkipHeader() Set whether to skip the header row true

Process Control

// Kill a running process
$processor->killProcess($jobId);

// Check process status
$status = $processor->getStatus($jobId);

// Check status for all processes owned by a user
$status = $processor->getStatusByOwner($userId);

Status Response Format

[
    'job_id' => 'csv_123456789',
    'total_process' => 100,
    'total_success' => 95,
    'total_failed' => 5,
    'total_inserted' => 80,
    'total_updated' => 15,
    'total_skip_empty_row' => 3,
    'display_id' => 'progress-bar-1',
    'estimate_time' => [
        'hours' => 0,
        'minutes' => 5,
        'seconds' => 30
    ],
    'file_name' => 'users.csv',
    'status' => 2, // 1=Pending, 2=Processing, 3=Completed, 4=Failed
    'error_message' => '[]',
    'percentage_completion' => '10',
    'last_check' => '2024-01-05 12:34:56'
]

Frontend Integration Example

function checkProgress(jobId) {
  $.ajax({
    url: "/your-controller/check-progress",
    data: { job_id: jobId },
    success: function (response) {
      if (response.status == 3) {
        // Process completed
        $("#progress-bar-1").html("Import completed!");
      } else if (response.status == 4) {
        // Process failed
        $("#progress-bar-1").html("Import failed: " + response.error_message);
      } else {
        // Update progress
        let progress = response.percentage_completion;
        $("#progress-bar-1").css("width", progress + "%");
        $("#progress-bar-1").html(`${progress}% (${response.total_success} succeeded, ${response.total_failed} failed)`);

        // Check again in 2 seconds
        setTimeout(() => checkProgress(jobId), 2000);
      }
    },
  });
}

📊 Status Codes Reference

Code Status Description
1 Pending Job created, waiting to start
2 Processing Currently processing the file
3 Completed Processing finished successfully
4 Failed Processing encountered an error

⚙️ Callback Response Format

The callback function should return an array with the following structure:

// Success response
return [
    'code' => 200,
    'action' => 'create', // or 'update'
    'message' => 'Success message'
];

// Error response
return [
    'code' => 500,
    'error' => 'Error message'
];

🔒 Process Management Features

CPU Load Management

The system automatically monitors server CPU load and manages processes accordingly:

  • Delays process start if CPU load is above 90%
  • Continuously monitors load during processing
  • Platform-specific CPU monitoring (Linux uses mpstat, Windows uses wmic)

Process Recovery

  • Automatic cleanup of orphaned processes
  • Lock file management to prevent duplicate processing
  • Graceful handling of interrupted processes

Memory Management

  • Chunk-based processing to control memory usage
  • Configurable memory limits
  • Automatic garbage collection
  • Database connection management to prevent leaks

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

The MIT License (MIT). Please see License File for more information.

💖 Support

If you find this library helpful, please consider giving it a star on GitHub!

onlyphp/codeigniter3-csvimporter 适用场景与选型建议

onlyphp/codeigniter3-csvimporter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 27 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 01 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「mysql」 「codeigniter」 「codeigniter3」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 onlyphp/codeigniter3-csvimporter 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 onlyphp/codeigniter3-csvimporter 我们能提供哪些服务?
定制开发 / 二次开发

基于 onlyphp/codeigniter3-csvimporter 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 27
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 29
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-04