È necessario implementare l'importazione csv o xls nell'applicazione creata utilizzando CodeIgniter. C'è qualche libreria per questo? Ogni suggerimento è apprezzato.Libreria di importazione CSV per CodeIgniter
risposta
Ecco un modo semplice per farlo. Non so cosa fanno le persone, ma io uso questo
Questo è il mio csv biblioteca lettore
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class CSVReader {
var $fields; /** columns names retrieved after parsing */
var $separator = ';'; /** separator used to explode each line */
var $enclosure = '"'; /** enclosure used to decorate each field */
var $max_row_size = 4096; /** maximum row size to be used for decoding */
function parse_file($p_Filepath) {
$file = fopen($p_Filepath, 'r');
$this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
$keys_values = explode(',',$this->fields[0]);
$content = array();
$keys = $this->escape_string($keys_values);
$i = 1;
while(($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
if($row != null) { // skip empty lines
$values = explode(',',$row[0]);
if(count($keys) == count($values)){
$arr = array();
$new_values = array();
$new_values = $this->escape_string($values);
for($j=0;$j<count($keys);$j++){
if($keys[$j] != ""){
$arr[$keys[$j]] = $new_values[$j];
}
}
$content[$i]= $arr;
$i++;
}
}
}
fclose($file);
return $content;
}
function escape_string($data){
$result = array();
foreach($data as $row){
$result[] = str_replace('"', '',$row);
}
return $result;
}
}
?>
e il metodo
function readExcel()
{
$this->load->library('csvreader');
$result = $this->csvreader->parse_file('Test.csv');
$data['csvData'] = $result;
$this->load->view('view_csv', $data);
}
controller e questo è vista
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width = "10%">ID</td>
<td width = "20%">NAME</td>
<td width = "20%">SHORT DESCRIPTION</td>
<td width = "30%">LONG DESCRIPTION</td>
<td width = "10%">STATUS</td>
<td width = "10%">PARENTID</td>
</tr>
<?php foreach($csvData as $field){?>
<tr>
<td><?php echo $field['id']?></td>
<td><?php echo $field['name']?></td>
<td><?php echo $field['shortdesc']?></td>
<td><?php echo $field['longdesc']?></td>
<td><?php echo $field['status']?></td>
<td><?php echo $field['parentid']?></td>
</tr>
<?php }?>
</table>
Riferimento Here
Questa è una versione migliorata di risposta accettata Raheel di shan - Ho modificato la sua risposta, ma la mia modifica è stata respinta, tuttavia si tratta di un cambiamento importante ...
Durante l'analisi di ogni riga di dati, non è saggio usare explode()
su la virgola in questo modo non gestisce stringhe con quote racchiuse che contengono virgole. Explode pause quelle stringhe in sottostringhe e dà elementi di un array supplementari in $values
, quindi questo controllo ha esito negativo:
if (count($keys) == count($values)) {
Invece, PHP ha un metodo costruito appositamente per gestire questa situazione; str_getcsv(). Ho aggiornato il codice di risposta originale di conseguenza.
La biblioteca CSV Reader:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class CSVReader {
var $fields;/** columns names retrieved after parsing */
var $separator = ';';/** separator used to explode each line */
var $enclosure = '"';/** enclosure used to decorate each field */
var $max_row_size = 4096;/** maximum row size to be used for decoding */
function parse_file($p_Filepath) {
$file = fopen($p_Filepath, 'r');
$this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
$keys = str_getcsv($this->fields[0]);
$i = 1;
while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
if ($row != null) { // skip empty lines
$values = str_getcsv($row[0]);
if (count($keys) == count($values)) {
$arr = array();
for ($j = 0; $j < count($keys); $j++) {
if ($keys[$j] != "") {
$arr[$keys[$j]] = $values[$j];
}
}
$content[$i] = $arr;
$i++;
}
}
}
fclose($file);
return $content;
}
}
?>
controller metodo:
function readExcel() {
$this->load->library('csvreader');
$result = $this->csvreader->parse_file('Test.csv');
$data['csvData'] = $result;
$this->load->view('view_csv', $data);
}
E questa è la vista:
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width="10%">ID</td>
<td width="20%">NAME</td>
<td width="20%">SHORT DESCRIPTION</td>
<td width="30%">LONG DESCRIPTION</td>
<td width="10%">STATUS</td>
<td width="10%">PARENTID</td>
</tr>
<?php foreach ($csvData as $field) { ?>
<tr>
<td><?php echo $field['id'] ?></td>
<td><?php echo $field['name'] ?></td>
<td><?php echo $field['shortdesc'] ?></td>
<td><?php echo $field['longdesc'] ?></td>
<td><?php echo $field['status'] ?></td>
<td><?php echo $field['parentid'] ?></td>
</tr>
<?php } ?>
</table>
Beh non mi importa, ho solo modificato ajmedway di libreria per includere delimitatori nel caso in cui si desidera ottenere dati da dire file TSV o tubi delimitati. Se vuoi semplicemente il vecchio CSV, va bene.
class CSVReader {
var $fields;/** columns names retrieved after parsing */
var $separator = ';';/** separator used to explode each line */
var $enclosure = '"';/** enclosure used to decorate each field */
var $max_row_size = 4096;/** maximum row size to be used for decoding */
function parse_file($p_Filepath, $delimiter = FALSE) {
$file = fopen($p_Filepath, 'r');
$this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
if ($delimiter==FALSE)
{
$keys = str_getcsv($this->fields[0]);
$i = 1;
while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
if ($row != null) { // skip empty lines
$values = str_getcsv($row[0]);
if (count($keys) == count($values)) {
$arr = array();
for ($j = 0; $j < count($keys); $j++) {
if ($keys[$j] != "") {
$arr[$keys[$j]] = $values[$j];
}
}
$content[$i] = $arr;
$i++;
}
}
}
}
else{
$keys = str_getcsv($this->fields[0],$delimiter);
$i = 1;
while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {
if ($row != null) { // skip empty lines
$values = str_getcsv($row[0],$delimiter);
if (count($keys) == count($values)) {
$arr = array();
for ($j = 0; $j < count($keys); $j++) {
if ($keys[$j] != "") {
$arr[$keys[$j]] = $values[$j];
}
}
$content[$i] = $arr;
$i++;
}
}
}
}
fclose($file);
return $content;
}}?>
Questo è sbagliato se ($ delimitatore = FALSO) mentre si imposta $ delimiter su FALSE e non si controlla lo stato. Dovrebbe essere se ($ delimit == FALSE) – Johnish
whoops! Scusate. Errore Rookie. Grazie a @Johnish. Lo correggerò immediatamente. –
Questa è una versione migliorata per le linee vuote e gli spazi in eccesso e le schede ...
class CSVReader {
function csv_to_array($Filepath)
{
//Get csv file content
$csvData = file_get_contents($Filepath);
//Remove empty lines
$csvData = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $csvData);
//String convert in array formate and remove double quote(")
$array = array();
$array = $this->escape_string(preg_split('/\r\n|\r|\n/', $csvData));
$new_content_in_array = array();
if($array)
{
//Get array key
$array_keys = array();
$array_keys = array_filter(array_map('trim', explode(';',$array[0])));
//Get array value
$array_values = array();
for ($i=1;$i<count($array);$i++)
{
if($array[$i])
{
$array_values[] = array_filter(array_map('trim', explode(';',$array[$i])));
}
}
//Convert in associative array
if($array_keys && $array_values)
{
$assoc_array = array();
foreach ($array_values as $ky => $val)
{
for($j=0;$j<count($array_keys);$j++){
if($array_keys[$j] != "" && $val[$j] != "" && (count($array_keys) == count($val)))
{
$assoc_array[$array_keys[$j]] = $val[$j];
}
}
$new_content_in_array[] = $assoc_array;
}
}
}
return $new_content_in_array;
}
function escape_string($data){
$result = array();
foreach($data as $row){
$result[] = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", str_replace('"', '',$row));
}
return $result;
}
} >
chiamata controller:?
$this->load->library('csvreader');
$import_csv_data = $this->csvreader->csv_to_array($path);
print_r($import_csv_data);
exit;
- 1. Accelera importazione csv
- 2. Importazione csv PostgreSQL da esportazione csv MySQL?
- 3. Codeigniter REST CSV import a mysql
- 4. Importazione di un file CSV in Java
- 5. Caricamento di un csv in Codeigniter
- 6. Importazione di dati CSV con POI Apache
- 7. Libreria PHP per convertire JSON in CSV?
- 8. contenuto oggetto ritaglio in importazione csv
- 9. importazione file csv da sito FTP esterno
- 10. libreria statica v.s. libreria di importazione su piattaforma Windows
- 11. Importazione di classi della libreria in Python
- 12. Errore di importazione di Cassandra .csv: batch troppo grande
- 13. Sequel pro - Importazione file CSV: errore di codifica
- 14. Importazione di dati da .csv con d3.js
- 15. mostra heatmap su libreria Codeigniter googlemap v3
- 16. Come adattare una libreria PHP a Codeigniter?
- 17. Codeigniter carica il modello nella libreria
- 18. Qualsiasi buona libreria per leggere e scrivere file CSV?
- 19. Collegamento alla libreria di importazione Python in Visual Studio 2005
- 20. .jar Importazione di libreria Android nel progetto Xamarin
- 21. In MySQL Workbench, l'utilizzo di "Importazione guidata dati tabella" per importare CSV crea una tabella vuota
- 22. Importazione di libreria e file locali in un'applicazione
- 23. Chiamare una libreria dall'interno di una funzione helper in Codeigniter
- 24. Importazione di file remoti tramite importazione ES6
- 25. È possibile chiamare una libreria codeigniter all'interno di un altro file di libreria?
- 26. Intestazioni di colonne in CSV utilizzando la libreria fileHelpers?
- 27. JAVA - import CSV per ArrayList
- 28. Codeigniter: quando utilizzare un modello o una libreria?
- 29. Caricare una libreria in un modello in CodeIgniter
- 30. Lavoro CRON per codeigniter
Thx Raheel, hai implementato questo per inserire anche csv nel database? –
sì basta passare '$ result' alla tabella del database o formare un array in base alle proprie esigenze. –