首页 > 代码库 > 数组转xml

数组转xml




/*
一维数组转xml
思路:
循环数组每个单元,加入到xml文档节点中去
*/

/*
$arr = array(
‘name‘=> ‘丁三‘,
‘age‘=>29
);


function arr2xml($arr) {
    $simxml = new simpleXMLElement(‘<?xml version="1.0" encoding="utf-8"?><root></root>‘);
    // simpleXMLElement对象如何增加子节点?

    foreach($arr as $k=>$v) {
        $simxml->addChild($k,$v);
    }

    return $simxml->saveXML();
}
*/


$arr = array(
‘name‘=> ‘丁三‘,
‘age‘=>29,
‘job‘=>array(
        ‘title‘=>‘经理‘,
        ‘salary‘=>8888,
        ‘team‘=>array(‘小红‘,‘小明‘,‘小华‘)
    )
);


function arr2xml($arr,$node=null) {
    if($node === null) {
        $simxml = new simpleXMLElement(‘<?xml version="1.0" encoding="utf-8"?><root></root>‘);
    } else {
        $simxml = $node;
    }
    // simpleXMLElement对象如何增加子节点?

    foreach($arr as $k=>$v) {
        if(is_array($v)) {
            //$simxml->addChild($k);
            arr2xml($v,$simxml->addChild($k));
        } else if(is_numeric($k)) {
           $simxml->addChild(‘item‘ . $k,$v);
        } else {
            $simxml->addChild($k,$v);
        }
    }

    return $simxml->saveXML();
}


header(‘content-type: text/xml‘);
echo arr2xml($arr);

数组转xml