Getting xlsx file with HTML and PHP

1

I need to import data xlsx to a system I've created.

HTML

<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="arquivo">
    <input type="submit" name="pegar value="pegar">
</form>

PHP

<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

if (isset($_POST['pega'])) {

   $arquivo = $_FILES['arquivo'];
   $file = fopen($arquivo,"r");

   while(! feof($file)){
       echo fgets($file). "<br />";
   }

   fclose($file);
}

And these are the error messages that appear:

  

Warning: fopen () expects parameter 1 to be a valid path, array given   in   /Applications/MAMP/htdocs/sistemas/scripts_da_web/php/importaCSV.php   online 20

     

Warning: feof () expects parameter 1 to be resource, boolean given in   /Applications/MAMP/htdocs/sistemas/scripts_da_web/php/importaCSV.php   online 22

     

Warning: fgets () expects parameter 1 to be resource, boolean given in   /Applications/MAMP/htdocs/sistemas/scripts_da_web/php/importaCSV.php   online 24

    
asked by anonymous 04.12.2015 / 20:15

1 answer

2

It is easier for you to do this by using the CSV (comma separated) file pattern. Use the PHPExcel library to convert your xlsx file to csv, and then use the fgetcsv function to transform the csv data into an array in php. Install the lib and complete your code with something like this:

$file = $_FILES['arquivo']['tmp_name'];
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$csvFileName = str_replace('.xlsx', '.csv', $file);
$objWriter->save($csvFileName);
if (($handle = fopen($csvFileName, "r")) !== false) {
    while (($data = fgetcsv($handle, 1000, ",")) !== false) {
        $num = count($data);
        echo "<p> $num campos na linha $row: <br /></p>\n";
        $row++;
        for ($c = 0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

Useful links:

link

link

    
04.12.2015 / 20:42