Hướng dẫn read csv file php - đọc tệp csv php

Have you tried forcing the line endings to be consistent? I've run into this before and had to add a PHP ini setting before parsing the CSV:

ini_set('auto_detect_line_endings',TRUE)

Put that before $reader

Edit via request in comments

Here's the class I use for CSVs, assuming you have at least PHP 5.5:

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}

You can use it like this:

$largeFile = new LargeFile($file);
// tell it use the CSV iterator
$iterator  = $largeFile->getIterator('Csv');

// start iterator and pull out header row as $rawHeaders
$rawHeaders = $iterator->current();

$headerIterator = new \ArrayIterator;
foreach ($rawHeaders as $header) {
    $headerIterator->append(strtolower("`$header`"));
}

$headers = $headerIterator->getArrayCopy();

// move pointer to the data rows
$iterator->next();

// loop through each row
foreach( $iterator as $row ) {
  // do stuff with each row
  print_r($row);
}

Tôi đã giới thiệu và hướng dẫn các bạn sử dụng thư viện PHPExcel tại địa chỉ http://gextend.net/threads/tao-bao-cao-excel-voi-thu-vien-phpexcel.17 để tạo các báo cáo Excel và bây giờ tôi tiếp tục hướng dẫn các bạn sử dụng thư viện mới nhất được chính nhà phát triển thư viện PHPExcel đề nghị tên là PhpSpreadsheet. Đây là thư viện có chức năng tương tự như PHPExcel nhưng được cải tiến rất nhiều về kiến trúc mã nguồn cũng như cho hiệu năng tốt hơn.

Thư viện PhpSpreadsheet hỗ trợ nhiều định dạng hơn PHPExcel.

Các định dạng cho phép đọc:

  • Open Document Format/OASIS (.ods).
  • Office Open XML (.xlsx) Excel 2007 and above.
  • BIFF 8 (.xls) Excel 97 and above.
  • BIFF 5 (.xls) Excel 95.
  • SpreadsheetML (.xml) Excel 2003.
  • Gnumeric.
  • HTML.
  • SYLK.
  • CSV.

Các định dạng cho phép ghi:

  • Open Document Format/OASIS (.ods).
  • Office Open XML (.xlsx) Excel 2007 and above.
  • BIFF 8 (.xls) Excel 97 and above.
  • HTML.
  • CSV.
  • PDF.

BIFF 5 (.xls) Excel 95.

SpreadsheetML (.xml) Excel 2003.

Các định dạng cho phép ghi:

Thư viện PhpSpreadsheet yêu cầu PHP phiên bản 5.6+ và các thư viện php_zip, php_xml và php_gd2.

composer require phpoffice/phpspreadsheet

Để sử dụng PhpSpreadsheet các bạn cần phải sử dụng công cụ composer. Các bạn tham khảo tại địa chỉ https://getcomposer.org.

Để cài đặt, các bạn chạy lệnh composer sau:

<?php
//Require tập tin autoload.php để tự động nạp thư viện PhpSpreadsheet
require 'path/to/vendor/autoload.php';

//Khai báo sử dụng các thư viện cần thiết
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

//Khởi tạo đối tượng spreadsheet
$spreadsheet = new Spreadsheet();

//Lấy bảng tính thao tác
$sheet = $spreadsheet->getActiveSheet();

//Nhập nội dung vào ô A1
$sheet->setCellValue('A1', 'Nội dung');

//Khởi tạo đối tượng writer
$writer = new Xlsx($spreadsheet);

//Lưu tập tin Excel
$writer->save('path/to/save/filename.xlsx');

Code:

Sau khi composer cài đặt thành công thư viện PhpSpreadsheet, các bạn có thể sử dụng thư viện như ví dụ sau:

PHP:

Các bạn có thể tham khảo thêm về thư viện PhpSpreadsheet tại địa chỉ https://github.com/PHPOffice/PhpSpreadsheet và https://phpspreadsheet.readthedocs.io.

As a Drupal developer, you might have come with a situation where you have to integrate Drupal websites with other third-party system. So here third party systems provide data in a CSV or excel format that we have to show in the Drupal website.

In this case, we have to import this data to one or more content type in Drupal.

composer require phpoffice/phpspreadsheet

There are excel import modules available that will do the job. But in these modules, you can use for direct import to content types. But most of the cases you have to work on each row to clean the data and also various validations on each data and assign to various content type based on conditions in cell values. For these purpose you have to write your own custom code.

So here I am going to explain how we can write our own excel import functionality in our custom module in Drupal 8.

“phpoffice/phpspreadsheet”: “^1.8”

before starting project. Install php spreadsheet  library using the below command in your project folder.

1) Import với phpoffice/phpspreadsheet

this will place phpspreadsheet library  in your vendors directory and adds below entry in your project composer.json.

You can see library in phpoffice folder inside your project vendors directory.

Here I have content type called news and trying to upload below sheet into the news content.

digitalnadeem_importexcel.import_excel:
  path: '/admin/structure/digitalnadeem_importexcel/sheet/import'
  defaults:
    _title: 'Upload sheet'
    _form: '\Drupal\digitalnadeem_importexcel\Form\ImportexcelForm'
  requirements:
    _permission: 'Import form'

Now we are going to create form in our custom module to import csv file and create content programmatically using phpspreadsheet library. Here my custom module name is digitalnadeem_importexcel

\src\Form\ImportexcelForm.php

First, we are creating custom form to import CSV or excel sheet.

For this, I have created a new entry in routing .yml file in my module.

Next I have created a form  ImportExcelForm.php in my module path.

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
0

First, you have to include spread sheet library classes as shown below

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
1

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
2

in buildForm function include the below code to create upload form.

Below the upload location, you have to create in your project directory.

In my case I have created in folder in below path.

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
3

So uploaded files will be stored in this path for processing.

As mentioned in form configuration I have provided csv format only allowed in validation. You can provide xlsx in an array if you are uploading a normal excel sheet.

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
4

Also added below validation function.

Now we are going to implement import functionality in our submit form handler.

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
5

In submit first we are getting file name that uploaded. And generating path to file uploaded directory .

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
6

Next we are using phpspreadsheet  functions to get extract cell values from uploaded document.

Ở đây hàng đầu tiên là hàng tiêu đề. Điều này chúng tôi không muốn nhập vào nội dung tin tức. Vì vậy, để loại bỏ sử dụng hàng đầu tiên bên dưới chức năng Array_shift.

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
7

Tiếp theo, chúng tôi lặp đi lặp lại thông qua mảng hàng $ để chèn các hàng vào nội dung tin tức.

Vì vậy, trước tiên chúng tôi sẽ kiểm tra nút Wether tồn tại bằng cách so sánh các trường tiêu đề.

SE bên dưới mã để tạo và cập nhật nút từ dữ liệu Excel.

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
8

Bây giờ bạn đã hoàn thành với việc thực hiện. Xóa bộ đệm bạn có thể thấy bên dưới biểu mẫu trong khi truy cập URL-& nbsp; http: //your-site.com/admin/structure/digitalnadeem_importexcel/sheet/import http://your-site.com/admin/structure/digitalnadeem_importexcel/sheet/import

Xem nội dung đã nhập trong trang nội dung quản trị viên.

2) Xuất VớI PHPOFFICE/PHPSPREADSHEET

<?php

use Exception;
use InvalidArgumentException;
use SplFileObject;
use NoRewindIterator;

class LargeFile {

const ERROR_UNABLE = 'ERROR: Unable to open file';
const ERROR_TYPE = 'ERROR: Type must be "ByLength", "ByLine", or "Csv"';

protected $file;
protected $allowed_types = [ 'ByLine', 'ByLength', 'Csv' ];

/**
 * LargeFile constructor.
 *
 * @param $filename
 * @param string $mode
 *
 * @throws Exception
 *
 * Populates $file with new SPL File object instance.
 */
public function __construct($filename, $mode = 'r') {
    if (!file_exists($filename)) {
        $message = __METHOD__ . ' : ' . self::ERROR_UNABLE . PHP_EOL;
        $message .= strip_tags($filename) . PHP_EOL;
        throw new Exception($message);
    }
    $this->file = new SplFileObject($filename, $mode);
}

/**
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with fgets.
 *
 * Suitable for smaller text files like Csvs and / or
 * include line feeds.
 */
protected function fileIteratorByLine() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgets();
        $count++;
    }
    return $count;
}

/**
 * @param $numBytes
 *
 * @return \Generator|int
 *
 * References SplFileObject method to read the file one line
 * at a time with freads.
 *
 * Suitable for larger binary files.
 */
protected function fileIteratorByLength($numBytes) {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fread($numBytes);
        $count++;
    }
    return $count;
}

protected function fileIteratorCsv() {
    $count = 0;

    while (!$this->file->eof()) {
        yield $this->file->fgetcsv();
        $count++;
    }
    return $count;
}

/**
 * @param string $type
 * @param null $numBytes
 *
 * @return NoRewindIterator
 */
public function getIterator($type = 'ByLine', $numBytes = null) {
    if (!in_array($type, $this->allowed_types)) {
        $message = __METHOD__ . ' : ' . self::ERROR_TYPE . PHP_EOL;
        throw new InvalidArgumentException($message);
    }
    $iterator = 'fileIterator' . $type;
    return new NoRewindIterator($this->$iterator($numBytes));
}
}
9

Sự kết luận

Ở đây tôi đã giải thích làm thế nào chúng ta có thể nhập một tờ Excel/CSV duy nhất vào Drupal. Hầu hết hệ thống bên thứ ba có thể có API có thể đặt bảng dữ liệu Excel/CSV vào một thư mục trong một khoảng thời gian thường xuyên. Trong đó & nbsp; trường hợp, & nbsp; làm theo cùng một cách tiếp cận mà tôi đã giải thích ở trên và một công việc tạo ra để lấy tệp từ một vị trí cụ thể. Vì vậy, Cron Job sẽ chèn nội dung từ Excel trong các khoảng thời gian đều đặn. Bằng cách này, bạn có thể tự động hóa toàn bộ quá trình.