2013-10-01 78 views
1

我的任務是將JSON數據轉換爲XML。現在,我的array_to_xml功能將數據從數組轉換爲:使用PHP將JSON轉換爲XML

<0>Maserati</0><1>BMW</1><2>Mercedes/2><3>Ford</3><4>Chrysler</4><5>Acura</5><6>Honda</6><0>1</0><1>2</1><2>1</2><3>0</3><4>4</4><5>0</5><6>0</6><0>1</0><1>2</1><2>1</2><3>0</3><4>4</4><5>0</5><6>0</6>

我想有以下格式的XML:

<Maserati> 1 </Maserati> 
    <BMW> 2 </BMW> 
    ... 

請看看在下面的PHP中,讓我知道所做的更改。 在此先感謝

$inpData = $_POST['data']; 
// initializing array 
$inp_info = $inpData; 
// creating object of SimpleXMLElement 
$xml_inp_info = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><demandSignals>\n</demandSignals>\n"); 
// function call to convert array to xml 
array_to_xml($inp_info,$xml_inp_info); 
//saving generated xml file 
$xml_inp_info->asXML(dirname(__FILE__)."/demand.xml") ; 
// function definition to convert array to xml 
function array_to_xml($inp_info, &$xml_inp_info) { 
     foreach($inp_info as $key => $value) { 

      if(is_array($value)) { 
       if(!is_numeric($key)){ 
        $subnode = $xml_inp_info->addChild("$key"); 
        if(count($value) >1 && is_array($value)){ 
         $jump = false; 
         $count = 1; 
         foreach($value as $k => $v) { 
          if(is_array($v)){ 
           if($count++ > 1) 
            $subnode = $xml_inp_info->addChild("$key"); 

           array_to_xml($v, "$subnode"); 
           $jump = true; 
          } 
         } 
         if($jump) { 
          goto LE; 
         } 
         array_to_xml($value, "\n$subnode"); 
         } 
        else 
         array_to_xml($value, $subnode); 
       } 
       else{ 
        array_to_xml($value, $xml_inp_info); 
       } 
      } 
      else { 

       $xml_inp_info->addChild("$key","$value"); 
      } 

      LE: ; 
     } 
    } 

回答