php解析XML

php php 1002      收藏
php解析XML

<?php
/**
 * 作为解析XML配置文件必备工具
 */
class XMLUtil {
    public static $dbconfigpath = "./db.config.xml";
    public static function getDBConfiguration() {
        $dbconfig = array ();
        try {
            // 读取配置文件内容
            $handle = fopen(self::$dbconfigpath, "r");
            $content = fread($handle, filesize(self::$dbconfigpath));
            // 获取xml文档根节点,进而获取相关的数据库信息
            $mysql = simplexml_load_string($content);
            // 将获取到的xml节点信息赋值给关联数组,方便接下来的方法调用
            $dbconfig['host'] = $mysql->host;
            $dbconfig['user'] = $mysql->user;
            $dbconfig['password'] = $mysql->password;
            $dbconfig['db'] = $mysql->db;
            $dbconfig['port'] = $mysql->port;
            // 将配置信息以关联数组的形式返回
            return $dbconfig;
        } catch ( Exception $e ) {
            throw new RuntimeException ( "<mark>读取数据库配置文件信息出错!</mark><br />" );
        }
        return $dbconfig;
    }
}