2016-07-25 72 views
2

我试过这个php数组格式。而转换为XML属性没有设置。如何在xml中添加属性

$request['Shopping'] = array( 
    "PTC"=>array(
    "_attributes" => array("Quantity" => "1"), 
    "_value" => "ADT") 
    ) 

function array_to_xml($array, &$xml_user_info) { 
foreach($array as $key => $value) { 
    if(is_array($value)) { 
     if(!is_numeric($key)){ 
      $subnode = $xml_user_info->addChild("$key"); 
      array_to_xml($value, $subnode); 
     }else{ 
      $subnode = $xml_user_info->addChild("item$key"); 
      array_to_xml($value, $subnode); 
     } 
    }else { 
     $xml_user_info->addChild("$key",htmlspecialchars("$value")); 
    } 
} 
} 

$xml_user_info = new SimpleXMLElement("<?xml version=\"1.0\"?><user_info>  </user_info>"); 
array_to_xml($request,$xml_user_info); 
$xml_file = $xml_user_info->asXML('users1.xml'); 
if($xml_file){ 
    echo 'XML file have been generated successfully.'; 
}else{ 
    echo 'XML file generation error.'; 
} 

我需要这个数组在下面的XML格式

<PTC Quantity="1">ADT</PTC> 

但我越来越喜欢this.Kindly给出一些解决方案。在此先感谢

<PTC> 
     <_attributes> 
     <Quantity>1</Quantity> 
     </_attributes> 
     <_value>ADT</_value> 
    </PTC> 
+0

显示您的实际代码,你正在处理XML结构(打开,解析) – RomanPerekhrest

+0

难道这还不够@roaman – Pravin

回答

0

对于你的情况,请在链接上使用的PHP类:http://www.lalit.org/wordpress/wp-content/uploads/2011/07/Array2XML.html?ver=0.8

并以此为下面的代码。

<?php 
//Put above class library in same folder of below code library and include it so the class functions can be used. 
include("array2xml.php"); 
//Format your array as below 
$PTC = array(
    '@attributes' => array(
     'Quantity' => '1' 
    ), 
    '@value' => 'ADT', 
); 
$xml = Array2XML::createXML('PTC', $PTC); 
echo $xml->saveXML(); 
?> 
+0

你检查我的解决方案? –

+0

它没有返回正确的XML格式,但谢谢你的答案 – Pravin

+0

你是否在页面执行后检查了视图源中创建的XML。因为我已经检查过,它正在生成与您需要的问题完全相同的xml。 –