XlsxParser.php 2.31 KB
<?php
/**
 * Created by PhpStorm.
 * User: Tsurkanov
 * Date: 21.10.2015
 * Time: 15:44
 */

namespace yii\multiparser;


use common\components\CustomVarDamp;


class XlsxParser extends Parser {
    public $path_for_extract_files = '';

    public function setup()
    {
        parent::setup();
        if ( $this->path_for_extract_files == '' ) {
            $this->path_for_extract_files = sys_get_temp_dir();
        }
    }


    public function read()
    {
        //$this->extractFiles();
        CustomVarDamp::dumpAndDie($this->parse());

       // return $this->parse();
    }

    protected function extractFiles ()
    {
        $zip = new \ZipArchive;
        if ( $zip->open( $this->file->getPathname() ) === TRUE ) {
            $zip->extractTo( $this->path_for_extract_files );
            $zip->close();
        } else {
            throw new \Exception('Ошибка чтения xlsx файла');
        }
    }

    protected function parse ()
    {
        $result = [];
       // while ($sheet = @readdir($this->file)) {
        foreach ( glob($this->path_for_extract_files . '/xl/worksheets/*.xml' ) as $sheet ) {
            //проходим по всем файлам из директории /xl/worksheets/
            //CustomVarDamp::dumpAndDie($sheet);
            if ($sheet != "." && $sheet != ".." && $sheet != '_rels') {
                $xml = simplexml_load_file( $sheet );
                //по каждой строке
                $row = 0;

                foreach ( $xml->sheetData->row as $item ) {
                    $result[$sheet][$row] = array();
                    //по каждой ячейке строки
                    $cell = 0;
                    foreach ( $item as $child ) {
                       // $attr = $child->attributes();

                            if( isset($child->v) ) {
                                $value = (string)$child->v;
                            }else{
                                $value = false;
                            }

                      //  $result[$sheet][$row][$cell] = isset($attr['t']) ? $sharedStringsArr[$value] : $value;
                        $result[$sheet][$row][$cell] = $value;
                        $cell++;
                    }
                    $row++;
                }
            }
        }
        return $result;
    }
}