Leitor de CSV/TSV

Inphinit\Experimental\Delimited\Csv e Inphinit\Experimental\Delimited\Tsv consegue ler arquivos CSV e TSV com suporte à compatibilidade com versões anteriores.

Os formatos CSV (Valores Separados por Vírgula) e TSV (Valores Separados por Tabulação) são formatos de texto simples para armazenar dados tabulares. Eles são amplamente adotados por serem simples, leves e facilmente portáveis entre diferentes plataformas.

Ler arquivo CSV

Um arquivo contendo o seguinte conteúdo:

Name,Age,Location Autumn,25,New York Olivia 30,Seul Josh,35,Singapore

Pode ser lido da seguinte forma:

use Inphinit\Experimental\Delimited\Csv; $handle = new Csv('file.csv'); echo '<h2>Headers:</h2>'; echo '<pre>'; var_dump($handle->getHeaders()); echo '</pre>'; echo '<h2>Contents:</h2>'; echo '<pre>'; while ($line = $handle->fetch()) { var_dump($line); }

saída:

Headers: array(3) { [0]=> string(4) "Name" [1]=> string(3) "Age" [2]=> string(8) "Location" } Contents: array(3) { [0]=> string(6) "Autumn" [1]=> string(2) "25" [2]=> string(8) "New York" } array(3) { [0]=> string(6) "Olivia" [1]=> string(2) "30" [2]=> string(4) "Seul" } array(3) { [0]=> string(4) "Josh" [1]=> string(2) "35" [2]=> string(9) "Singapore" }

Leia TSV

Um arquivo contendo o seguinte conteúdo:

Name Age Location Autumn 25 New York Olivia 30 Seul Josh 35 Singapore

Pode ser lido assim:

use Inphinit\Experimental\Delimited\Tsv; $handle = new Tsv('file.tsv'); echo '<h2>Headers:</h2>'; echo '<pre>'; var_dump($handle->getHeaders()); echo '</pre>'; echo '<h2>Contents:</h2>'; echo '<pre>'; while ($line = $handle->fetch()) { var_dump($line); }

Bandeiras

O comportamento de leitura pode ser alterado usando os métodos Csv::setFlags()`and` .Tsv::setFlags()

$handle = new Csv('file.csv'); $handle->setFlags(Csv::MODE_COLUMN|Csv::SKIP_EMPTY|Csv::SKIP_HEADER); while ($line = $handle->fetch()) { var_dump($line); }

saída:

array(3) { ["Name"]=>string(6) "Autumn" ["Age"]=>string(2) "25" ["Location"]=>string(8) "New York" } array(3) { ["Name"]=>string(6) "Olivia" ["Age"]=>string(2) "30" ["Location"]=>string(4) "Seul" } array(3) { ["Name"]=>string(4) "Josh" ["Age"]=>string(2) "35" ["Location"]=>string(9) "Singapore" }
Constante Descrição
MODE_COLUMN As linhas serão retornadas como matrizes associativas, usando os cabeçalhos como chaves.
MODE_INDEX As linhas serão retornadas como matrizes indexadas (padrão).
SKIP_EMPTY Linhas vazias serão ignoradas e não serão retornadas.fetch()
SKIP_HEADER A linha com cabeçalhos não será retornada em fetch(), mas ainda estará presente em getHeaders()
STRICT Documentos cujo cabeçalho possui apenas uma coluna, por não ter sido encontrado um separador compatível, serão considerados inválidos.

Objeto de Transferência de Dados (DTO)

É possível desserializar as linhas em instâncias de uma classe específica:

use Model\User; $handle = new Csv('file.csv'); $handle->setDataTransferObject(User::class);
object(Model\User)#39 (3) { ["Name"]=>string(6) "Autumn" ["Age"]=>string(2) "25" ["Location"]=>string(8) "New York" }

Usando stdClass:

use Model\User; $handle = new Csv('file.csv'); $handle->setDataTransferObject('stdClass');
object(stdClass)#39 (3) { ["Name"]=>string(6) "Autumn" ["Age"]=>string(2) "25" ["Location"]=>string(8) "New York" }

Fim da linha

Alguns arquivos CSV mais antigos podem ter quebras de linha que são incomuns hoje em dia; nesses casos, você pode ajustar o final da linha:

$handle = new Csv('file.csv'); $handle->setEndOfLine("\r");

Convertendo

Após ler e filtrar um arquivo CSV/TSV, você pode exportá-lo e até mesmo convertê-lo para outros formatos ou tabelas.

Convertendo para JSON

$handle = new Csv('file.csv'); $handle->converter()->json('output[index].json', false);
$handle = new Csv('file.csv'); $handle->converter()->json('output[pairs].json', true);

Convertendo para CSV

$handle = new Csv('file.csv'); // Changing the separator $handle->converter()->csv('output.csv', ';'); // Changing the separator and the enclosure $handle->converter()->csv('output.csv', ';', '"'); // Changing the separator, enclosure, and end-of-line $handle->converter()->csv('output.csv', ';', '`', "\r\n");

Convertendo para TSV

$handle = new Csv('file.csv'); // Save to TSV format $handle->converter()->tsv('output.tsv'); // Changing the end-of-line $handle->converter()->tsv('output.tsv', "\r\n");

Convertendo para HTML e XML

É possível converter usando DOMDocument, permitindo criar HTML ou XML, por exemplo:

use Inphinit\Http\Response; use Inphinit\Experimental\Delimited\Csv; $handle = new Csv('file.csv'); $xml = new DOMDocument; $main = $xml->createElement('Main'); $xml->appendChild($main); $handle->setFilter(function (array &$fields, $index) { // Handle values present in the headers. if ($index === 0) { foreach ($fields as &$field) { $field = preg_replace('#[^\w]+#', '-', $field); $field = preg_replace('#-{2,}#', '-', $field); } } else { foreach ($fields as &$field) { $field = stripcslashes($field); } } }); $handle->converter()->dom($main); Response::type('application/xml'); echo $xml->saveXML();
Página inicial
Apoie com uma estrela no GitHub