我们经常会用到缓存数据就是把数组保存成xml文档方便处理,下面我们提供一个数组转换成xml文档的类,有需要的朋友可以参考一下.
php数组转换成xml文件php类代码如下:
- <?php
- $elementLevel = 0 ;
- function array_Xml($array, $keys = '')
- {
- global $elementLevel;
- if(!is_array($array))
- {
- if($keys == ''){
- return $array;
- }else{
- return "n<$keys>" . $array . "</$keys>";
- }
- }else{
- foreach ($array as $key => $value)
- {
- $haveTag = true;
- if (is_numeric($key))
- {
- $key = $keys;
- $haveTag = false;
- }
-
-
-
- if($elementLevel == 0 )
- {
- $startElement = "<$key>";
- $endElement = "</$key>";
- }
- $text .= $startElement."n";
-
-
-
- if(!$haveTag)
- {
- $elementLevel++;
- $text .= "<$key>" . array_Xml($value, $key). "</$key>n";
- }else{
- $elementLevel++;
- $text .= array_Xml($value, $key);
- }
- $text .= $endElement."n";
- }
- }
- return $text;
- }
-
- class ArrayToXML
- {
-
-
-
-
-
-
-
-
-
- public static function toXml($data, $rootNodeName = 'data', $xml=null)
- {
-
- if (ini_get('zend.ze1_compatibility_mode') == 1)
- {
- ini_set ('zend.ze1_compatibility_mode', 0);
- }
- if ($xml == null)
- {
- $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
- }
-
- foreach($data as $key => $value)
- {
-
- if (is_numeric($key))
- {
-
- $key = "unknownNode_". (string) $key;
- }
-
- $key = preg_replace('/[^a-z]/i', '', $key);
-
- if (is_array($value))
- {
- $node = $xml->addChild($key);
-
- ArrayToXML::toXml($value, $rootNodeName, $node);
- }
- else
- {
-
- $value = htmlentities($value);
- $xml->addChild($key,$value);
- }
- }
-
- return $xml->asXML();
- }
- }
-
-
- function arrtoxml($arr,$dom=0,$item=0){
- if (!$dom){
- $dom = new DOMDocument("1.0");
- }
- if(!$item){
- $item = $dom->createElement("root");
- $dom->appendChild($item);
- }
- foreach ($arr as $key=>$val){
- $itemx = $dom->createElement(is_string($key)?$key:"item");
- $item->appendChild($itemx);
- if (!is_array($val)){
- $text = $dom->createTextNode($val);
- $itemx->appendChild($text);
- }else {
- arrtoxml($val,$dom,$itemx);
- }
- }
- return $dom->saveXML();
- }
- ?>
|