27 December, 2010

Excel to Array in PHP

Customer's data can come from various sources, and making it easier for them to get the data into our system means we are increasing our customer's count. So, our code should support importing of data from different sources.
And one of the common sources can be Excel. So, we need to create an interface for customers so that they can load data from excel to our database.
Instead of spending hours entering data into forms, users can simply use tools such as excel to load data from excel using php.
In the following code, we load data from excel in php, read it and display the data back to the users. The displaying of data part can be replaced by inserting the loaded excel data to database to suit individual needs. And we are
using XML to do this.

Let's say we have a form "form.php" as:


Now after user adds an excel file and uploads it, following code "do_act.php" is executed,

$dataArr = array();
if($_FILES["excelFle"]["tmp_name"]) {
$xmlDom = DOMDocument::load($_FILES["excelFle"]["tmp_name"]);
$allRows = $xmlDom->getElementsByTagName('Row');
//loop through each of the row element
foreach($allRows as $row) {
$cells = $row->getElementsByTagName('Cell');
$rowData = array();
foreach($cells as $cell) {
$rowData []= $cell->nodeValue;
$dataArr []= $rowData;

//so now you can check for the array of data as:
echo "
echo "

No comments: