代码改变世界

XML和MYSQL转换--PHP实现

2011-04-28 16:46  卫佳  阅读(430)  评论(0编辑  收藏  举报

mysql2xml.php类文件:用于备份MySQL数据的!

PHP代码

  1. <?php   
  2. class MySQL2XML {   
  3.         protected $conn;   
  4.         protected $result;   
  5.         protected $tables;   
  6.         protected $saveFolder = 'datas/';   
  7.            
  8.         public function __construct($config = NULL) {   
  9.                 if($config !== NULL && is_array($config)) {   
  10.                         $this->connect($config);   
  11.                 }   
  12.         }   
  13.            
  14.         public function connect($config) {   
  15.                 $this->conn = mysql_connect($config['host'], $config['username'], $config['password']);   
  16.                 if($this->conn) {   
  17.                         mysql_select_db($config['database']);   
  18.                         return true;   
  19.                 }   
  20.                 return false;   
  21.         }   
  22.            
  23.         public function setSaveFolder($folder) {   
  24.                 if(is_dir($folder)) {   
  25.                         $this->saveFolder = rtrim(str_replace("\\", "/", $folder),'/');  
  26.                         return true;  
  27.                 }  
  28.                 return false;  
  29.         }  
  30.           
  31.         public function setTables($tables) {  
  32.                 if(is_array($tables)) {  
  33.                         $this->tables = $tables;  
  34.                         return true;  
  35.                 }  
  36.                 return false;  
  37.         }  
  38.           
  39.         public function query($query) {  
  40.                 if(!isset($query) || trim($query) == '') return false;  
  41.                 $this->result = mysql_query($query);  
  42.                 if($this->result) return true;  
  43.                 return false;  
  44.         }  
  45.           
  46.         public function toXML() {  
  47.                 if(!isset($this->tables)) return false;  
  48.                 foreach($this->tables as $table) {  
  49.                         $file = $this->saveFolder.$table.'.xml';  
  50.                         $fp = @fopen($file, 'w');  
  51.                         if(!$fp) exit('Can not write file');  
  52.                         fwrite($fp, $this->tableToXML($table));  
  53.                         fclose($fp);  
  54.                         unset($fp);  
  55.                 }  
  56.                 return true;  
  57.         }  
  58.           
  59.         public function tableToXML($table) {  
  60.                 header("content-type:text/xml;charset=utf-8");  
  61.                 $xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<datas>\n";   
  62.                 $fields = $this->getFields($table);   
  63.                 $datas = $this->getDatas($table);   
  64.                 $cdata = array();   
  65.                 foreach($datas as $data) {   
  66.                         foreach($data as $key => $value)   
  67.                                 $cdata[$key][] = $value;   
  68.                 }   
  69.                 foreach($fields as $element) {   
  70.                         $xml .= "\t<fields name=\"{$element['Field']}\" type=\"{$element['Type']}\" null=\"{$element['Null']}\" key=\"{$element['Key']}\" default=\"{$element['Default']}\" extra=\"{$element['Extra']}\">\n";   
  71.                         foreach($cdata[$element['Field']] as $value) {   
  72.                                 $xml .= "\t\t<data>{$value}</data>\n";   
  73.                         }   
  74.                         $xml .= "\t</fields>\n";   
  75.                 }   
  76.                 $xml .= '</datas>';   
  77.                 return $xml;   
  78.         }   
  79.            
  80.         protected function getFields($table) {   
  81.                 $query = "SHOW FIELDS FROM {$table}";   
  82.                 $this->query($query);   
  83.                 return $this->fetchAll();   
  84.         }   
  85.            
  86.         protected function getDatas($table) {   
  87.                 $query = "SELECT * FROM {$table}";   
  88.                 $this->query($query);   
  89.                 return $this->fetchAll();   
  90.         }   
  91.            
  92.         protected function fetch() {   
  93.                 if(is_resource($this->result)) {   
  94.                         return mysql_fetch_assoc($this->result);   
  95.                 }   
  96.                 return false;   
  97.         }   
  98.            
  99.         protected function fetchAll() {   
  100.                 if(is_resource($this->result)) {   
  101.                         $return = array();   
  102.                         $row = NULL;   
  103.                         while($row = mysql_fetch_assoc($this->result)) {   
  104.                                 $return[] = $row;   
  105.                         }   
  106.                         return $return;   
  107.                 }   
  108.                 return false;   
  109.         }   
  110. }   
  111. ?>  

调用方法:

PHP代码

  1. <?php   
  2. $xml = new MySQL2XML(array('host'=>'localhost', 'username'=>'root', 'password'=>'', 'database'=>'mysql'));   
  3. $xml->setTables(array('wp_term_relationships','wp_terms'));//设置备份的表   
  4. $xml->setSaveFolder('datas/');//保存备份文件的文件夹   
  5. $xml->toXML();//备份开始   
  6. ?>  

还原数据的类:

xml2mysql.php类文件:用来还原MySQL数据的

PHP代码

  1. <?php   
  2. require_once 'mysql2xml.php';   
  3. class XML2MySQL extends MySQL2XML {   
  4.         private $XMLFiles = array();   
  5.         private $tableName = NULL;   
  6.         private $fields = array();   
  7.         private $datas = array();   
  8.            
  9.         public function __construct($config = NULL) {   
  10.                 parent::__construct($config);   
  11.                 if(!function_exists('simplexml_load_file')) throw new Exception("Your server isn't suppost this class.");   
  12.         }   
  13.            
  14.         public function setXMLFiles($file) {   
  15.                 if(is_array($file)) {   
  16.                         foreach($file as $f) {   
  17.                                 if(file_exists($f)) {   
  18.                                         $this->XMLFiles[] = $f;   
  19.                                         return true;   
  20.                                 } else return false;   
  21.                         }   
  22.                 } else {   
  23.                         if(file_exists($file)) {   
  24.                                 $this->XMLFiles[] = $file;   
  25.                                 return true;   
  26.                         } else return false;   
  27.                 }   
  28.         }   
  29.            
  30.         public function getXMLFromFolder($dir) {   
  31.                 if(!is_dir($dir)) return false;   
  32.                 $dir = rtrim(str_replace("\\", "/", $dir), '/').'/';  
  33.                 $dp = @opendir($dir);  
  34.                 if(!$dp) throw new Exception("Can not open folder");  
  35.                 while(($f = readdir($dp)) !== false) {  
  36.                         if($f != '.' && $f != '..') {  
  37.                                 if(!$this->setXMLFiles($dir.$f)) throw new Exception("Error:Files are not xml file or files are not exists.");  
  38.                         }  
  39.                 }  
  40.                 closedir($dp);  
  41.                 return true;  
  42.         }  
  43.           
  44.         public function toMySQL() {  
  45.                 $buff = '';  
  46.                 foreach($this->XMLFiles as $xml) {  
  47.                         $this->getDataFromXML($xml);  
  48.                         $drop = 'DROP TABLE IF EXISTS `'.$this->tableName.'`;';  
  49.                         if($this->query($drop)) $buff .= 'Drop table <font color="red">['.$this->tableName.']</font> <font color="green">success</font>'."<br/>\n";  
  50.                         else $buff .= 'Drop table <font color="red">['.$this->tableName.']</font> <font color="red">fail</font>'."<br/>\n";  
  51.                         $pk = NULL;  
  52.                         $uk = NULL;  
  53.                         $sql = 'CREATE TABLE `'.$this->tableName."`(\n";  
  54.                         foreach($this->fields as $field) {  
  55.                                 $sql .= '`'.$field['name'].'`'.' '.$field['type'].' '.($field['null'] == 'NO' ? 'NOT NULL ':'').(trim($field['extra']) != '' ? strtoupper($field['extra']).' ' : '').(trim($field['default']) != '' ? 'DEFAULT '."'".$field['default']."'" : '').','."\n";  
  56.                                 if($field['key'] == 'PRI') $pk = $pk.(strpos($pk, 'PRIMARY KEY') !== FALSE ? '`'.$field['name'].'`,' : 'PRIMARY KEY (`'.$field['name'].'`,');  
  57.                                 if($field['key'] == 'UNI') $uk = $uk.(strpos($uk, 'UNIQUE KEY') !== FALSE ? '`'.$field['name'].'`,' : "UNIQUE KEY `".$field['name']."` (`".$field['name']."`,");  
  58.                                 $fields[$this->tableName][] = $field['name'];  
  59.                         }  
  60.                         if($pk !== NULL) {  
  61.                                 $pk = rtrim($pk, ",")."),\n";  
  62.                                 $sql .= $pk;  
  63.                         }  
  64.                         if($uk !== NULL) {  
  65.                                 $uk = rtrim($uk, ",")."),\n";  
  66.                                 $sql .= $uk;  
  67.                         }  
  68.                         $sql = rtrim($sql, ",\n");  
  69.                         $sql .= ');';  
  70.                         if($this->query($sql)) $buff .= 'Create table <font color="red">['.$this->tableName.']</font> <font color="green">success</font>'."<br/>\n";  
  71.                         else $buff .= 'Create table <font color="red">['.$this->tableName.']</font> <font color="red">fail</font>'."<br/>\n";  
  72.                         unset($sql);  
  73.                           
  74.                         $datas = 'INSERT INTO `'.$this->tableName.'` (';  
  75.                         foreach($fields as $table_name => $f) {  
  76.                                 foreach($f as $element) {  
  77.                                         $datas .= '`'.$element.'`,';  
  78.                                 }  
  79.                         }  
  80.                         $this->datas = $this->r2l($this->datas);  
  81.                         $datas = rtrim($datas, ',').') VALUES ';  
  82.                         foreach($this->datas as $data) {  
  83.                                 $datas .= "(";  
  84.                                 foreach($data as $d) {  
  85.                                         $datas .= "'".$d."',";  
  86.                                 }  
  87.                                 $datas = rtrim($datas, ',');  
  88.                                 $datas .= '),';  
  89.                         }  
  90.                         $datas = rtrim($datas, ',').';';  
  91.                         if($this->query($datas)) $buff .= 'Insert data in table <font color="red">['.$this->tableName.']</font> <font color="green">success</font>'."<br/><br/>\n";  
  92.                         else $buff .= 'Insert data in table <font color="red">['.$this->tableName.']</font> <font color="red">fail</font>'."<br/><br/>\n";   
  93.                         unset($fields);   
  94.                 }   
  95.                 return $buff;   
  96.         }   
  97.            
  98.         private function r2l($array) {   
  99.                 $temp = array();   
  100.                 for($i = 0; $i < count($array); $i++) {   
  101.                         for($j = 0; $j < count($array[0]); $j++) {   
  102.                                 $temp[$j][$i] = $array[$i][$j];   
  103.                         }   
  104.                 }   
  105.                 return $temp;   
  106.         }   
  107.            
  108.         private function getDataFromXML($xml) {   
  109.                 //Use the SimpleXML Object   
  110.                 $this->tableName = substr(basename($xml), 0, strlen(basename($xml)) - 4);   
  111.                 $simplexml = simplexml_load_file($xml);   
  112.                 $fields = array();   
  113.                 $index = 0;   
  114.                 foreach($simplexml->children() as $e) {   
  115.                         $fields[$index]['name'] = (string)$e->attributes()->name;  
  116.                         $fields[$index]['type'] = (string)$e->attributes()->type;  
  117.                         $fields[$index]['null'] = (string)$e->attributes()->null;  
  118.                         $fields[$index]['key']  = (string)$e->attributes()->key;  
  119.                         $fields[$index]['default'] = (string)$e->attributes()->default;  
  120.                         $fields[$index]['extra'] = (string)$e->attributes()->extra;   
  121.                         $index++;   
  122.                 }   
  123.                 $this->fields = $fields;   
  124.                    
  125.                 $datas = array();   
  126.                 $index = 0;   
  127.                 foreach($simplexml->children() as $e) {   
  128.                         foreach($e->children() as $d) {   
  129.                                 $datas[$index][] = (string)$d;   
  130.                         }   
  131.                         $index++;   
  132.                 }   
  133.                 $this->datas = $datas;   
  134.         }   
  135. }   
  136. ?>  

调用方法:

PHP代码

  1. <?php   
  2. $s = new XML2MySQL(array('host'=>'localhost', 'username'=>'root', 'password'=>'', 'database'=>'mysql'));   
  3. $s->getXMLFromFolder('datas/');//备份文件的文件夹(就是装XML文件的文件夹)   
  4. echo $s->toMySQL();//此方法返回还原消息   
  5. ?>