0

Excel file:

enter image description here

PHP code (excel to array):

function excel_to_array($excel_file) {
    $filename = dirname(dirname(__FILE__)) .'/admin/user_files/' . $excel_file['name'];
    $type = PHPExcel_IOFactory::identify($filename);
    $objReader = PHPExcel_IOFactory::createReader($type);
    $objPHPExcel = $objReader->load($filename);

    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
        $worksheets[] = $worksheet->toArray();
    }

    var_dump($worksheets);
}

Result:

array (size=1)
    0 =>
        array (size=2)
            0 =>
                array (size=1)
                    0 => string '0894090592' (length=10)
            1 =>
                array (size=1)
                    0 => string '0894040404' (length=10)

There is too much nested arrays for such a simple excel, I'm lookig for something like this:

$worksheets = ['0894090592', '0894040404'];

Is there a way ?

P.S: I will NOT have multiple columns, but will have more rows, like these!

2
  • No!if you have multiple data on multiple rows and columns Which format is more easy to handle ? Commented Jul 9, 2019 at 9:12
  • 2
    Seems to be structured as worksheet-id row-id column-id. You will need to extract your data if you want it to look more simple. Commented Jul 9, 2019 at 9:15

2 Answers 2

1

Extracting the data:

function excel_to_array($excel_file) {
    $filename = dirname(dirname(__FILE__)) .'/admin/user_files/' . $excel_file['name'];
    $type = PHPExcel_IOFactory::identify($filename);
    $objReader = PHPExcel_IOFactory::createReader($type);
    $objPHPExcel = $objReader->load($filename);
    $worksheets = array();

    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
        $worksheetArray= $worksheet->toArray();
        foreach($worksheetArray as $row) {
            if(isset($row[0])) {
                $worksheets[] = $row[0];
            }
        }
    }

    var_dump($worksheets);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_column to get only the values in [0].

function excel_to_array($excel_file) {
    $filename = dirname(dirname(__FILE__)) .'/admin/user_files/' . $excel_file['name'];
    $type = PHPExcel_IOFactory::identify($filename);
    $objReader = PHPExcel_IOFactory::createReader($type);
    $objPHPExcel = $objReader->load($filename);

    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
        $worksheets[] = $worksheet->toArray();
    }

    // Here we get only the values to a flat array
    $worksheets = array_column($worksheets, 0);
    var_dump($worksheets);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.