Domanda

I am wondering whether it is possible to read a specific value from CSV specifed the row number and column number.

Lets say I want to read data from row number 44 and column number K?

I dont want to parse through the complete CSV. How to read specific data?

Hope I am clear with my question? Any answer would be appreciated.

È stato utile?

Soluzione

CSV files have no index, so you would need at least to go to the 44th line and retrieve it:

$file = new SplFileObject($path);
$file->setFlags(SplFileObject::READ_CSV);
$single = new LimitIterator($file, $offset = 43, $limit = 1);
list($row) = iterator_to_array($single, false);
$k = 10;
echo $row[$k];

Altri suggerimenti

Here is a function that accepts the path to a CSV file, and inserts all records to the given MySQL table, paying attention to the column names: 

<?php 
function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) { 
    if (($handle = fopen("$source_file", "r")) !== FALSE) { 
        $columns = fgetcsv($handle, $max_line_length, ","); 
        foreach ($columns as &$column) { 
            $column = str_replace(".","",$column); 
        } 
        $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES"; 
        while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) { 
            while (count($data)<count($columns)) 
                array_push($data, NULL); 
            $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");"; 
            mysql_query($query); 
        } 
        fclose($handle); 
    } 
} 

function quote_all_array($values) { 
    foreach ($values as $key=>$value) 
        if (is_array($value)) 
            $values[$key] = quote_all_array($value); 
        else 
            $values[$key] = quote_all($value); 
    return $values; 
} 

function quote_all($value) { 
    if (is_null($value)) 
        return "NULL"; 

    $value = "'" . mysql_real_escape_string($value) . "'"; 
    return $value; 
} 
?> 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top