How to create structured array from Tabdelimited file with PHP?

前端 未结 2 1402
不知归路
不知归路 2021-02-09 03:38

I have a problem with reading a tab delimited file.

The structure on my file is:

Field 1     Field 2     Field 3
Element11   Element12   Element13
Elemen         


        
2条回答
  •  孤城傲影
    2021-02-09 03:52

    To also get the headers as array keys you need

    $result = array();
    $fp = fopen('/path/to/file','r');
    if (($headers = fgetcsv($fp, 0, "\t")) !== FALSE)
      if ($headers)
        while (($line = fgetcsv($fp, 0, "\t")) !== FALSE) 
          if ($line)
            if (sizeof($line)==sizeof($headers))
              $result[] = array_combine($headers,$line);
    fclose($fp);
    print_r($result);
    

提交回复
热议问题