XLS to XML conversion using PHP

$lib =  libraries_load('PHPExcel'); //load PHPExcel library
  include $lib['library path'].'/IOFactory.php'; 
 //conveert xls to csv
            $objReader = PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($url);
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
            $path_to_file = $file_path."/".$file_name.'.csv';
            $objWriter->save($path_to_file);
            //convert csv to XML
            $csv = file($path_to_file);
              $xml_array = array();
                foreach($csv as $line){
                    $xml_key = explode(",", $line);
                    break;
                }
                $count =count($xml_key);
                $_key = array();
                for($i=0;$i< $count; $i++){
                 $_parsed_data = str_replace('"', '', $xml_key[$i]);
                 $_parsed_data = str_replace('(', '_', $_parsed_data);
                 $_parsed_data = str_replace(')', '_', $_parsed_data);
                 $_parsed_data = str_replace(' ', '_', $_parsed_data);
                 array_push($_key, strtolower($_parsed_data));
                 }
                 $xml_key = $_key;
                
            $data =array();
            foreach($csv as $line){
                 $line = str_replace('"', '', $line);
                 $line = str_replace('(', '_', $line);
                 $line = str_replace(')', '_', $line);
                $data[] = explode(",", $line);
            }
             $count = count($xml_key);
            for ($j = 0; $j < $count; $j++) {
               $text = $xml_key[$j];
               $data_new = $data_new."<".$text."></".$text.">";        
            }
            array_shift($data);
            foreach ($data as $key => $value) {
              $xml_new = $xml_new."<data>";
              foreach ($value as $new_key => $new_value) {
                $text = $xml_key[$new_key];
                  $new_value = str_replace('&', '&amp;', $new_value);
                  $parsed_field  = !empty(trim ($new_value)) ? trim($new_value) : ' ';
                 $xml_new = $xml_new."<".$text.">".$parsed_field."</".$text.">";   
                }
               $xml_new = $xml_new."</data>";
            }
            $xml_new = "<datas>".$xml_new."</datas>";
            $prepared_xml ='<?xml version="1.0"?>'.$xml_new;
            header('Content-disposition: attachment; filename='.$file_name.'.xml');
            header('Content-type: application/xml');
            echo $prepared_xml;

Leave a Comment.