TSV File to PHP Array

This function lets you take a tab separated text file (or comma separated, pipe separated, etc.) and convert it into a PHP array with just one line of code. Huge time saver.

It's similar to the CSV to Array function that we posted, but different in that it doesn't use PHP's built-in fgetcsv function. This gives you some extra flexibility, including the option to open a TSV file instead of a CSV file.

$args is an optional array that you can pass in to set options. If you set $args['tab'] to "," the file can handle a CSV file instead of TSV. Change it to "|" and it will handle pipe separated text. You get the idea…

The other items in the $args array should be fairly self-explanatory or have inline comments to help you out.

Here's the function itself:

1.   <?php
2.   
3.   // TSV to Array Function
4.   // Copyright (c) 2015, Ink Plant
5.   // https://inkplant.com/code/
6.   // this version was last updated June 23, 2015
7.   
8.   function tsv_to_array($file,$args=array()) {
9.   	//key => default
10.  	$fields = array(
11.  		'header_row'=>true,
12.  		'remove_header_row'=>true,
13.  		'trim_headers'=>true, //trim whitespace around header row values
14.  		'trim_values'=>true, //trim whitespace around all non-header row values
15.  		'debug'=>false, //set to true while testing if you run into troubles
16.  		'lb'=>"\n", //line break character
17.  		'tab'=>"\t", //tab character
18.  	);
19.  	foreach ($fields as $key => $default) {
20.  		if (array_key_exists($key,$args)) { $$key = $args[$key]; }
21.  		else { $$key = $default; }
22.  	}
23.  
24.  	if (!file_exists($file)) {
25.  		if ($debug) { $error = 'File does not exist: '.htmlspecialchars($file).'.'; }
26.  		else { $error = 'File does not exist.'; }
27.  		custom_die($error);
28.  	}
29.  
30.  	if ($debug) { echo '<p>Opening '.htmlspecialchars($file).'&hellip;</p>'; }
31.  	$data = array();
32.  
33.  	if (($handle = fopen($file,'r')) !== false) {
34.  		$contents = fread($handle, filesize($file));
35.  		fclose($handle);
36.  	} else {
37.  		custom_die('There was an error opening the file.');
38.  	}
39.  
40.  	$lines = explode($lb,$contents);
41.  	if ($debug) { echo '<p>Reading '.count($lines).' lines&hellip;</p>'; }
42.  
43.  	$row = 0;
44.  	foreach ($lines as $line) {
45.  		$row++;
46.  		if (($header_row) && ($row == 1)) { $data['headers'] = array(); }
47.  		else { $data[$row] = array(); }
48.  		$values = explode($tab,$line);
49.  		foreach ($values as $c => $value) {
50.  			if (($header_row) && ($row == 1)) { //if this is part of the header row
51.  				if (in_array($value,$data['headers'])) { custom_die('There are duplicate values in the header row: '.htmlspecialchars($value).'.'); }
52.  				else {
53.  					if ($trim_headers) { $value = trim($value); }
54.  					$data['headers'][$c] = $value.''; //the .'' makes sure it's a string
55.  				}
56.  			} elseif ($header_row) { //if this isn't part of the header row, but there is a header row
57.  				$key = $data['headers'][$c];
58.  				if ($trim_values) { $value = trim($value); }
59.  				$data[$row][$key] = $value;
60.  			} else { //if there's not a header row at all
61.  				$data[$row][$c] = $value;
62.  			}
63.  		}
64.  	}
65.  
66.  	if ($remove_header_row) {
67.  		unset($data['headers']);
68.  	}
69.  
70.  	if ($debug) { echo '<pre>'.print_r($data,true).'</pre>'; }
71.  	return $data;
72.  }
73.  
74.  ?>

Just click the Download link, save that file, include it and then use something like this to generate your array:

1.   //load the function
2.   require_once 'tsv-to-array.inc.php';
3.   
4.   //open up your file and convert it to an array
5.   $file = 'my_file.tsv';
6.   $data = tsv_to_array($file,array('header_row'=>true,'remove_header_row'=>true));
7.   
8.   //this will print out the array to the screen
9.   echo '<pre>'.print_r($data,true).'</pre>';

That's all there is to it. If you run into problems because your file is too big, I recommend switching to a CSV (if possible) and using our CSV to Array PHP function instead – it can handle bigger files.


Comments

Loading…

This post was first published on May 4th, 2015 and last updated on June 23rd, 2015 by Robert James Reese in PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.