CSV to XML Conversion using PHP

CSV to XML Conversion using PHP.

$csv = file($url); //path to file
              $xml_array = array();
                foreach($csv as $line){
                    $xml_key = explode(",", $line);
                    break;
                }
            $data =array();
            foreach($csv as $line){
                $data[] = explode(",", $line);
            }
            $count = count($xml_key);
            for ($j = 0; $j < $count; $j++) {
               $text = strtolower(str_replace(' ', '_', $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 = strtolower($xml_key[$new_key]);
                 $text =  strtolower(str_replace('(', '_', $text));
                 $text =  strtolower(str_replace(')', '_', $text));
                 $new_value = str_replace('&', '&amp;', $new_value);
                 $parsed_field  = !empty(trim ($new_value)) ? trim($new_value) : ' ';
                 $x = trim($new_value) ? 'yes' : 'no';
                 $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.