EXCEL to XML Converter using Javascript and PHP

If you want to convert excel file to xml you can use the tool we created. You can also see the source code of how to convert xlsx file to xml. Javascript and PHP languages are used to create this converter. Using javascript we send the user uploaded file to PHP file. In PHP we convert the uploaded file and we get the XML code.

How to Download PHPExcel Library?

There are many options available for download PHPExcel library. Checkout below links:

Excel to XML conversion steps:

  1. Upload file
  2. Check file is valid or not.
  3. Sent for conversion
  4. Check how much Sheets in Excel file
  5. Convert all Sheets into associate array
  6. Convert array to XML
  7. Show result

How to get Excel file by user?


<input accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" id="file_upload">

How to find out file has been uploaded or not? If uploaded, then how to check if the file size is more or less than 2MB?

document.querySelector("#file_upload").onchange = function() {
    if(document.querySelector('#file_upload').files.length == 0) {
		alert('Error : No file selected');
		return;
	}
	var file = document.querySelector('#file_upload').files[0];
	
	if(file.size > 2*1024*1024) {
		alert('Error : Exceeded size 2MB');
		return;
	}
}

Send Excel file to PHP using AJAX:

var data = new FormData();
data.append('file', document.querySelector('#file_upload').files[0]);
var request = new XMLHttpRequest();
request.open('post', '../code/exceltojson.php');
request.addEventListener('load', function(e) {
    // code
});
request.send(data);

Check file is Excel or not in PHP

$valid = false;
$types = array('Excel2007', 'Excel5');
foreach ($types as $type) {
    $reader = PHPExcel_IOFactory::createReader($type);
    if ($reader->canRead($file)) {
        $valid = true;
        break;
    }
}

if ($valid) {
    // Excel file is Valid
} else {
    // Excel file is not valid
}

Convert file Excel to array:

$index = 0;
$data = Array();
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

    $objPHPExcel->setActiveSheetIndex($index);
    
    $sheetData = $worksheet->toArray(null, true, true, true);
    
    $result = Array();
    $keys = $sheetData[1];
    for ($i = 2; $i < count($sheetData); $i++) {
        $rowValue = Array();
        $row = $sheetData[$i];
        foreach($row as $key=>$value) {
            if ($keys[$key] != "") {
                $rowValue[$keys[$key]] = $value;
            }
        }
        for ($j = 0; $j < count($row); $j++) {
            
        }
        $result[] = $rowValue;
    }
    
    $data[str_replace(array("-"," "), "_", $worksheet->getTitle())] = $result;
    $index++;
}

Convert PHP Associate array to XML:


function array2xml($array, $xml = false){

    if($xml === false){
        $xml = new SimpleXMLElement('<result/>');
    }

    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $xml->addChild($key));
        } else {
            $xml->addChild($key, $value);
        }
    }

    return $xml->asXML();
}

SOURCE CODE:

excel-to-xml-converter.html


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

<div class="item-wrapper one">
<div class="item">
    <form action="exceltoxml.php" method="post" enctype="multipart/form-data">
        <div class="item-inner">
            <div class="item-content">
                <div class="image-upload"> <label style="cursor: pointer;" for="file_upload">
                        <div class="h-100">
                            <div class="dplay-tbl">
                                <div class="dplay-tbl-cell"> <i class="fa fa-cloud-upload"></i>
                                    <h5><b>Choose Your file to Upload</b></h5>
                                    <h6 class="mt-10 mb-70">Or Drop Your File Here</h6>
                                </div>
                            </div>
                        </div>
                        <!--upload-content--> <input accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" name="excelfile" id="file_upload" class="image-input" required>
                    </label> </div>
            </div>
            <!--item-content-->
        </div>
        <!--item-inner-->
    </form>
</div>
<!--item-->
</div>
<progress id="progress" value="0"></progress>

<div class="form-group">
    <label>Result:</label>
    <textarea id="result" class="prettyprint form-control" rows="15"></textarea>
</div>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.11.0/beautify-html.js"></script>
<script>
    document.querySelector("#progress").style.display = "none";

    $(document).ready(function() {
        document.querySelector("#file_upload").onchange = function() {
        if(document.querySelector('#file_upload').files.length == 0) {
            alert('Error : No file selected');
            return;
        }
        var file = document.querySelector('#file_upload').files[0];
        
        if(file.size > 2*1024*1024) {
            alert('Error : Exceeded size 2MB');
            return;
        }

        if (document.querySelector("#pre") !== null) {
            document.querySelector("#pre").remove();
        }

        var data = new FormData();
        data.append('file', document.querySelector('#file_upload').files[0]);
        document.querySelector("#progress").style.display = "block";
        var request = new XMLHttpRequest();
        request.open('post', '../code/code.php?type=exceltoxml');
        
        request.upload.addEventListener('progress', function(e) {
            var percent_complete = (e.loaded / e.total)*100;
            document.querySelector("#progress").max = 100;
            document.querySelector("#progress").value = percent_complete;
        });

        request.addEventListener('load', function(e) {
            var beautify_html = html_beautify(request.response);
            document.querySelector("#result").value = beautify_html;
            document.querySelector('#file_upload').value = "";
            document.querySelector("#progress").value = 0;
            document.querySelector("#progress").style.display = "none";

            document.querySelector('#file_upload').value = "";
        });
        request.send(data);
        
    };
    });
</script>


excel-to-xml-converter.php


ini_set('memory_limit', '2000M');

require_once 'Classes/PHPExcel/IOFactory.php';

if (isset($_FILES["file"])) {
    
    $file = "files/".basename($_FILES["file"]["name"]);
    move_uploaded_file($_FILES["file"]["tmp_name"], $file);

    $valid = false;
    $types = array('Excel2007', 'Excel5');
    foreach ($types as $type) {
        $reader = PHPExcel_IOFactory::createReader($type);
        if ($reader->canRead($file)) {
            $valid = true;
            break;
        }
    }
    
    if ($valid) {
        
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        $objPHPExcel = $objReader->load($file);
    
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');    
    
        $index = 0;
        $data = Array();
        foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    
            $objPHPExcel->setActiveSheetIndex($index);
            
            $sheetData = $worksheet->toArray(null, true, true, true);
            
            $result = Array();
            $keys = $sheetData[1];
            for ($i = 2; $i < count($sheetData); $i++) {
                $rowValue = Array();
                $row = $sheetData[$i];
                foreach($row as $key=>$value) {
                    if ($keys[$key] != "") {
                        $rowValue[$keys[$key]] = $value;
                    }
                }
                for ($j = 0; $j < count($row); $j++) {
                    
                }
                $result[] = $rowValue;
            }
            
            $data[str_replace(array("-"," "), "_", $worksheet->getTitle())] = $result;
            $index++;
        }
        
        $xml = array2xml($data, false);
        print_r($xml);
    } else {
        echo "{\"status\":\"Error\", \"reason\":\"Not Valid Excel file.\"}";
    }
    
} else {
    echo "{\"status\":\"Error\", \"reason\":\"Please select file.\"}";
}

function array2xml($array, $xml = false){

    if($xml === false){
        $xml = new SimpleXMLElement('<result/>');
    }

    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $xml->addChild($key));
        } else {
            $xml->addChild($key, $value);
        }
    }

    return $xml->asXML();
}