* * localhost * username * password * mydb * * * Table1
*
* export-result.xml *
* * Anforderungen: * * PHP 5.1 (PDO, XMLWriter) * MySQL x.x * * @author Christoph * @version 1.0 */ if (count($argv) < 2) die("Usage: export.php config.xml"); $configFile = $argv[1]; if (!file_exists($configFile)) die("Configuration file $configFile does not exist."); function entity($match) { return '&#'.ord($match[1]).';'; } $config = simplexml_load_file($configFile); $host = $config->host; $username = $config->username; $password = $config->password; $database = $config->database; $tables = count($config->tables->table) ? $config->tables : array(); $dsn = "mysql:database=$database;host=$host"; try { $db = new PDO($dsn, $username, $password); $db->query("USE $database"); } catch (PDOException $e) { die("Connection failed: ".$e->getMessage()); } print "Connection to $database@$host established.\n"; if (empty($tables)) { print "Querying tables..."; foreach ($result = $db->query("SHOW TABLES") as $row) { $tables[] = $row[0]; } print " done.\n"; } $xml = new XMLWriter(); $xml->openMemory(); $xml->setIndent(true); $xml->setIndentString("\t"); $xml->startElement("dataset"); foreach ($tables as $table) { print "Exporting table $table..."; $xml->startElement("table"); $xml->writeAttribute("name", $table); foreach ($db->query("SHOW COLUMNS FROM $table") as $column) { $xml->writeElement("column", $column['Field']); } foreach ($db->query("SELECT * FROM $table", PDO::FETCH_NUM) as $row) { $xml->startElement("row"); foreach ($row as $column) { if ($column===null) $xml->writeElement("null"); else { $column = preg_replace_callback('#([\x00-\x1F])#i', 'entity', $column); $column = iconv('ISO-8859-1','UTF-8', $column); $xml->startElement("value"); $xml->writeCData($column); $xml->endElement(); } } $xml->endElement(); } $xml->endElement(); print " done.\n"; } $xml->endElement(); $bytes = file_put_contents( $config->exportFile, ''."\n".$xml->flush() ); unset($xml); if ($bytes === false) { print "Error writing dataset to ".$config->exportFile."!\n"; } else { print "Exported dataset to ".$config->exportFile." (".number_format($bytes,0)." bytes written).\n"; } unset($db); print "Connection closed.\n"; ?>