[eluser]Sinclair[/eluser]
Hi,
Few time ago I have developed a few methods to deal with CSV files. I don't know if can help you.
I have a method that obtains the Headers of the CSV data:
Code:
public function obtainHeader($input_csv_file) {
// Vou apontar para a primeira linha
$row = 1;
// Vou apanhar a primeira linha que contém o Header
$handle = fopen($input_csv_file, "r");
// Vou apanhar a Excepção para o caso de o ficheiro n dar p abrir
if (!$handle) {
throw new Exception("Nao foi possivel abrir o ficheiro " . $input_csv_file . ", metodo em causa: obtainHeader()");
}
while (($data = fgetcsv($handle, 1000, ",")) && $row == 1) {
// Vou à primeira linha apanhar os Headers
if ($row == 1) {
// Vou colocar os campos numa variavel
$fields = implode(", ", $data);
}
// Vou passar para a próxima linha
$row = $row + 1;
}
// Fecha o ficheiro
$handle_close_file = fclose($handle);
// Vou apanhar a Excepção para o fecho do ficheiro
if (!$handle_close_file) {
throw new Exception("Nao foi possivel fechar o ficheiro " . $input_csv_file . ", metodo em causa: obtainHeader()");
}
return $fields;
}
And other method that inserts to the database:
Code:
public function insertLinesToDb($input_csv_file, $db_table, $table_header) {
// Vou fazer o tratamento de Excepções nos parametros
if (is_null($input_csv_file)) {
throw new Exception("O parametro input_csv_file e nulo, metodo em causa: insertLinesToDb()");
} elseif (is_null($db_table)) {
throw new Exception("O parametro db_table e nulo, metodo em causa: insertLinesToDb()");
} elseif (is_null($table_header)) {
throw new Exception("O parametro table_header e nulo, metodo em causa: insertLinesToDb()");
} else {
// Vou assignar o valor do $this->input_csv_file
$this->input_csv_file = $input_csv_file;
// Vou apontar para a primeira linha
$row = 1;
// Vou apanhar as linhas com dados
// Vou abrir o ficheiro
$handle = fopen($this->input_csv_file, "r");
// Vou fazer o tratamento de excepções ao $handle
if (!$handle) {
throw new Exception("Nao foi possivel abrir o ficheiro " . $input_csv_file . ", metodo em causa: insertLinesToDb()");
}
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// Para todas as outras linhas que não a primeira
if ($row >=2) {
$fields = implode("', '", $data);
$fields_final = "('" . $fields . "');";
// Vou inserir para a BD. Aqui nesta linha vou ter de chamar um método do model do CodeIgniter!!!!!!!!!!!!!!!
echo "INSERT INTO " . $db_table . " (" . $table_header . ") VALUES " . $fields_final;
}
// Vou passar para a próxima linha
$row = $row + 1;
}
$handle_close_file = fclose($handle);
// Vou fazer o tratamento de excepções ao $handle_close_file
if (!$handle_close_file) {
throw new Exception("Nao foi possivel fechar o ficheiro " . $input_csv_file . ", metodo em causa: insertLinesToDb()");
}
return $row . " registos inseridos na tabela \"" . $db_table . "\"";
}
}
This is not for working with excel files(but you can convert them to CSV), but I hope that give you an idea.