Xls to json conversion using PHP

Hey folks once again I am back with some useful code. Now we will see the code for xls to json conversion.

$lib =  @libraries_load('PHPExcel'); //load PHPExcel library
include $lib['library path'].'/IOFactory.php'; 
$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);
           //  return drupal_goto($path_to_file); 
            $feed = $path_to_file;
            $keys = array();
            $newArray = array();
            $data = csvToArray($feed, ',');
            $count = count($data) - 1;
            //Use first row for names 
            $labels = array_shift($data);
            foreach ($labels as $label) {
                $keys[] = $label;
            }
           // Add Ids, just in case we want them later
            $keys[] = 'id';
            for ($i = 0; $i < $count; $i++) {
                $data[$i][] = $i;
            }
            for ($j = 0; $j < $count; $j++) {
                $d = array_combine($keys, $data[$j]);
                $newArray[$j] = $d;
            }
           $json_data = json_encode($newArray);
           header('Content-disposition: attachment; filename='.$file_name.'.json');
           header('Content-type: application/json');
          echo $json_data;

Leave a Comment.