0

0

再来一个 数组转 XML

PHP中文网

PHP中文网

发布时间:2016-05-25 16:58:29

|

1608人浏览过

|

来源于php中文网

原创

php代码

魔法映像企业网站管理系统
魔法映像企业网站管理系统

技术上面应用了三层结构,AJAX框架,URL重写等基础的开发。并用了动软的代码生成器及数据访问类,加进了一些自己用到的小功能,算是整理了一些自己的操作类。系统设计上面说不出用什么模式,大体设计是后台分两级分类,设置好一级之后,再设置二级并选择栏目类型,如内容,列表,上传文件,新窗口等。这样就可以生成无限多个二级分类,也就是网站栏目。对于扩展性来说,如果有新的需求可以直接加一个栏目类型并新加功能操作

下载
saveXML();
 */

class Array2XML {

    private static $xml = null;
    private static $encoding = 'UTF-8';

    /**
     * Initialize the root XML node [optional]
     * @param $version
     * @param $encoding
     * @param $format_output
     */
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
        self::$xml = new DomDocument($version, $encoding);
        self::$xml->formatOutput = $format_output;
        self::$encoding = $encoding;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DomDocument
     */
    public static function &createXML($node_name, $arr=array()) {
    $xml = self::getXMLRoot();
    $xml->appendChild(self::convert($node_name, $arr));

    self::$xml = null;    // clear the xml node in the class for 2nd time use.
    return $xml;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DOMNode
     */
    private static function &convert($node_name, $arr=array()) {

    //print_arr($node_name);
    $xml = self::getXMLRoot();
    $node = $xml->createElement($node_name);

    if(is_array($arr)){
        // get the attributes first.;
        if(isset($arr['@attributes'])) {
            foreach($arr['@attributes'] as $key => $value) {
                if(!self::isValidTagName($key)) {
                    throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
                }
                $node->setAttribute($key, self::bool2str($value));
            }
            unset($arr['@attributes']); //remove the key from the array once done.
        }

        // check if it has a value stored in @value, if yes store the value and return
        // else check if its directly stored as string
        if(isset($arr['@value'])) {
            $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
            unset($arr['@value']);    //remove the key from the array once done.
            //return from recursion, as a note with value cannot have child nodes.
            return $node;
        } else if(isset($arr['@cdata'])) {
            $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
            unset($arr['@cdata']);    //remove the key from the array once done.
            //return from recursion, as a note with cdata cannot have child nodes.
            return $node;
        }
    }

    //create subnodes using recursion
    if(is_array($arr)){
        // recurse to get the node for that key
        foreach($arr as $key=>$value){
            if(!self::isValidTagName($key)) {
                throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
            }
            if(is_array($value) && is_numeric(key($value))) {
                // MORE THAN ONE NODE OF ITS KIND;
                // if the new array is numeric index, means it is array of nodes of the same kind
                // it should follow the parent key name
                foreach($value as $k=>$v){
                    $node->appendChild(self::convert($key, $v));
                }
            } else {
                // ONLY ONE NODE OF ITS KIND
                $node->appendChild(self::convert($key, $value));
            }
            unset($arr[$key]); //remove the key from the array once done.
        }
    }

    // after we are done with all the keys in the array (if it is one)
    // we check if it has any text value, if yes, append it.
    if(!is_array($arr)) {
        $node->appendChild($xml->createTextNode(self::bool2str($arr)));
    }

    return $node;
    }

    /*
     * Get the root XML node, if there isn't one, create it.
     */
    private static function getXMLRoot(){
        if(empty(self::$xml)) {
            self::init();
        }
        return self::$xml;
    }

    /*
     * Get string representation of boolean value
     */
    private static function bool2str($v){
        //convert boolean to text value.
        $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        return $v;
    }

    /*
     * Check if the tag name or attribute name contains illegal characters
     * Ref: http://www.w3.org/TR/xml/#sec-common-syn
     */
    private static function isValidTagName($tag){
        $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
        return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
    }
}
?>

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

65

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

43

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

35

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

41

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

204

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

9

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

8

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Excel 教程
Excel 教程

共162课时 | 10.3万人学习

Swoft2.x速学之http api篇课程
Swoft2.x速学之http api篇课程

共16课时 | 0.9万人学习

php初学者入门课程
php初学者入门课程

共10课时 | 0.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号