3
I rode a script for import of CSV
with PHP
but I’m having difficulty with checking the type of formatting CSV
. I need to check if he’s separated by ,
or ;
or \t
or :
or |
, but I’m not getting it.
Follows the Script:
<?php
$arquivo = isset($_FILES["file_csv"]) ? $_FILES["file_csv"] : FALSE;
$tipoValido = "text/comma-separated-values";
if($tipoValido != $arquivo["type"])
{
echo "Arquivo em formato inválido! O arquivo deve ser extensão CSV. Envie outro arquivo";
echo '<br/><a href="index.html">Fazer Upload de Outro Arquivos</a>';
}
else
{
preg_match("/\.(csv){1}$/i", $arquivo["name"], $ext);
$arquivo_nome = date("d-m-Y_H-i-s") . "." . $ext[1];
move_uploaded_file($arquivo["tmp_name"], $arquivo_nome);
$row = 0;
$handle = fopen ($arquivo_nome,"r");
echo "<table border=1>";
while ( $data = fgetcsv ($handle, 1000, ",") )
{
$num = count ($data);
$row++;
$coluna1 = $data[0];
$coluna2 = $data[1];
$coluna3 = $data[2];
$coluna4 = $data[3];
$coluna5 = $data[4];
//$query = "INSERT INTO tabela ( coluna1 , coluna2 , coluna3 ) VALUES ( '$coluna1' , '$coluna2' , '$coluna3', '$coluna4', '$coluna5' )";
//mysql_query($query) or die(mysql_error());
if ($row != 1)
{
echo "<tr>";
echo "<td>".$coluna1."</td>";
echo "<td>".$coluna2."</td>";
echo "<td>".$coluna3."</td>";
echo "<td>".$coluna4."</td>";
echo "<td>".$coluna5."</td>";
echo "</tr>";
}
}
echo "</table>";
echo "<p>Dados da planilha inseridos com sucesso!<br/>Total de linhas inseridas: ".$row."</p>";
fclose ($handle);
unlink($arquivo_nome);
}
?>
There are 5 fields this csv always?
– rray
@rray The idea is this, but if it is dynamic would be even better.
– MoisesGama
If you give a
explode
by any of these delimiters can know which is the right delimiter because it returns an array with some element– rray