Recently I have been writing an XLS/CSV parser in PHP for inserting records into a database. I wanted to implement a way to upload either a XLS/CSV file and for the data to be parsed and imported. Here is my implementation.

Implementation

For the CSV parser I used parseCSV:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
# include parseCSV class.
# create new parseCSV object.
$csv = new parseCSV();
$csv->auto('upload/'.$_FILES["file"]["name"]);
?>
<table border="0" cellspacing="1" cellpadding="3">
	<tr>
	<?php foreach ($csv->titles as $value): ?>
		<th><?php echo $value; ?></th>
	<?php endforeach; ?>
	</tr>
	<?php foreach ($csv->data as $key => $row): ?>
	<tr>
	<?php foreach ($row as $value): ?>
		<td><?php echo $value; ?></td>
	<?php endforeach; ?>
	</tr>
	<?php endforeach; ?>
</table>
?>

For the XLS parser I used PHP-ExcelReader.:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader();
// Set output Encoding.
$data->setOutputEncoding('CP1251');
$data->read('upload/'.$_FILES["file"]["name"]);
?>
<table border="0" cellspacing="1" cellpadding="3">
	<?php for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) { ?>
	<tr>
		<?php for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) { ?>
			<td><?php echo $data->sheets[0]['cells'][$i][$j]; ?></td>
		<?php } ?>
	</tr>
	<?php } ?>
</table>

Download

Click here to download the source.