如何在xml中添加属性

时间:2016-07-25 05:32:22

标签: php xml

我试过这个php数组格式。虽然没有设置转换为XML属性。

 Map<std::string, int>

我需要以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.';
}

但我会这样。请给出一些解决方案。提前致谢

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

1 个答案:

答案 0 :(得分:0)

对于您的情况,请在链接上使用php class: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();
?>