coder3
coder3

Reputation: 81

How can we get csv file's headers with php

We have a csv file like this:

HASTANEKODU,HASTANEADI,SEHIR,BOLGE,DONEM,DONEMKODU,
1128,"SİVAS NUMUNE HASTANESİ",Sivas,"İç Anadolu Bölgesi","KASIM 2010",01

I want to get only text of headers in this csv file as array .I tried this code.

$source = 'uploads/'.$_POST['source'];

$handle = fopen($source, "r"); 

$data = array();
while( ($line = fgetcsv($handle))) {
    $data[] = $line;
}

print_r($data);

But this code get all csv fields.

How can I achive this?

Thanks

Upvotes: 0

Views: 44

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

As the headers are the first line, then you just test whether you're reading the first line of the file, and do whatever you need different with that line

$data = array();
$headers = true;
while( ($line = fgetcsv($handle))) {
    if ($headers) {
        $headerline = $line;
        $headers = false;
    } else {
        $data[] = $line;
    }
}

Upvotes: 1

Related Questions