Hola, tengo este codigo para leer un archivo (lo subo en .csv)
Y cargo el archivo y lo guardo en una carpeta temporal.
Y despues quiero leerlo y cargarlo en una tabla...
pero no se puede leer a ver si alguien podria ayudarme
Saludos.
Código HTML:
<form action="csv.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" value="Subir" />
</form>
Código PHP:
$allowedExtensions = array("csv");
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
if (!in_array(end(explode(".",
strtolower($file['name']))),
$allowedExtensions)) {
die($file['name'].' is an invalid file type!<br/>'.
'<a href="javascript:history.go(-1);">'.
'<< Go Back</a>');
}
}
}
$fileloc = $_FILES['file']['name'];
echo "Your file is located at " . $fileloc . "\n" . "<br />";
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
$filename = "upload/" . $_FILES["file"]["name"] . "<br />";
echo "<br/> <br />" . "INCIANDO" . "<br />";
if ( $file = fopen($filename, "r") ) {
echo "File opened.<br />";
$firstline = fgetcsv ($file, 4096 );
//Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
$num = strlen($firstline) - strlen(str_replace(",", "", $firstline));
//save the different fields of the firstline in an array called fields
$fields = array();
$fields = explode( ",", $firstline, ($num+1) );
$line = array();
$i = 0;
//CSV: one line is one record and the cells/fields are seperated by ";"
//so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
while ( $line[$i] = fgets ($file, 4096) ) {
$dsatz[$i] = array();
$dsatz[$i] = explode( ",", $line[$i], ($num+1) );
$i++;
}
echo "<table>";
echo "<tr>";
for ( $k = 0; $k != ($num+1); $k++ ) {
echo "<td>" . $fields[$k] . "</td>";
}
echo "</tr>";
foreach ($dsatz as $key => $number) {
//new table row for every record
echo "<tr>";
foreach ($number as $k => $content) {
//new table cell for every field of the record
echo "<td>" . $content . "</td>";
}
}
echo "</table>";
}
}