Variable with temporary file path loses value in Function

Asked

Viewed 24 times

1

Hello. I am venturing into PHP using Phpspreadsheet and came across the following problem: I get the path of a temporary file and it loses its value when it enters Function.

Below is the code.

<?php 
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Helper\Sample;

error_reporting(E_ALL);

$helper = new Sample();

// Return to the caller script when runs by CLI
if ($helper->isCli()) {
    return;
}

use PhpOffice\PhpSpreadsheet\IOFactory;

// guarda o arquivo e a extensão dele
if(!empty($_FILES['arquivo']['tmp_name'])){
    $arquivo = $_FILES['arquivo']['tmp_name'];
    $extensao_arquivo = pathinfo($_FILES['arquivo']['name'], PATHINFO_EXTENSION);
} else {
    echo "Vazio";
}

switch ($extensao_arquivo) {
    case 'xlsx':
        $reader = IOFactory::createReader('Xlsx');
        lePlanilha();
        break;
    case 'xls':
        $reader = IOFactory::createReader('Xls');
        lePlanilha();
        break;
    default:
        # code...
        break;
}

function lePlanilha(){
    echo "Nome: " . $arquivo . " - Extensão: ". $extensao_arquivo . "<br>";
}

echo "Nome: " . $arquivo . " - Extensão: ". $extensao_arquivo . "<br>";

$spreadsheet = $reader->load($arquivo);

$worksheet = $spreadsheet->getActiveSheet();

$ultima_coluna = $worksheet -> getHighestColumn();
$total_colunas = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($ultima_coluna);
$total_linhas = $worksheet -> getHighestRow();

$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);

echo '<table>' . "\n";
for ($linha = 1; $linha <= $total_linhas; ++$linha) {
    echo '<tr>' . PHP_EOL;
    for ($coluna = 1; $coluna <= $total_colunas; ++$coluna) {
        $array_linhas[$linha][$coluna] = utf8_decode($worksheet->getCellByColumnAndRow($coluna, $linha)->getValue());
        echo '<td>' . $array_linhas[$linha][$coluna] . '</td>' . PHP_EOL;
    }
    echo '</tr>' . PHP_EOL;
}
echo '</table>' . PHP_EOL;

?>

Excerpt on the page:

Name: - Extension:

Name: /tmp/phpUfuxi3 - Extension: xlsx

Forgive me if the question is obvious.

1 answer

0

Set the function setting before the switch and with parameters and use the parameters in the function call:

function lePlanilha($arq, $extensao){
    echo "Nome: " . $arq . " - Extensão: ". $extensao . "<br>";
}

switch ($extensao_arquivo) {
    case 'xlsx':
        $reader = IOFactory::createReader('Xlsx');
        lePlanilha($arquivo, $extensao_arquivo);
        break;
    case 'xls':
        $reader = IOFactory::createReader('Xls');
        lePlanilha($arquivo, $extensao_arquivo);
        break;
    default:
        # code...
        break;
}
  • @Woss as soon as I answered, I realized this and adjusted, in parallel with his comment

  • Great. It worked fine. Thank you!

  • Glad you could help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.