note 59656 deleted from ref.xml by nlopess
| From: | nlopess@php.net | Date: | Mon, 12 Dec 2005 19:45:42 +0000 |
| Subject: | note 59656 deleted from ref.xml by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-100013@lists.php.net to get a copy of this message | ||
Note Submitter: memandeemail at gmail dot com
----
XML TO DB
XML Example:
<?xml version="1.0" encoding="iso-8859-1"?>
<data>
<table name="bairro" primary_key="hash">
<row>
<field name="hash">1</field>
<field name="descr">Centro</field>
</row>
</table>
<?php
class xmlToDB {
var $parser;
var $cn;
var $table;
var $recordset = array();
var $content;
var $value;
var $field;
function xmlToDB() {
$this->parser = xml_parser_create();
xml_set_object($this->parser,$this);
xml_set_element_handler($this->parser,"tag_open","tag_close");
xml_set_character_data_handler($this->parser,"cdata");
$this->cn = @mysql_pconnect(XOOPS_DB_HOST,XOOPS_DB_USER,XOOPS_DB_PASS) or
trigger_error('Erro ao conectar ao servidor de dados',E_USER_ERROR);
@mysql_select_db(XOOPS_DB_NAME,$this->cn) or trigger_error('Erro ao selecionar o banco
de dados',E_USER_ERROR);
}
function parse($data) {
@xml_parse($this->parser, $data) or
die(sprintf("Erro de XML: %s na linha %d",
xml_error_string(xml_get_error_code($this->parser)),
xml_get_current_line_number($this->parser)));
}
function tag_open($parser, $tag, $attributes) {
$parser;
switch ($tag) {
case 'DATA': break;
case 'TABLE': {
$this->table = $attributes['NAME'];
mysql_unbuffered_query("TRUNCATE $this->table");
$this->recordset = array();
//[todo]primary key não usada
} break;
case 'ROW': break;
case 'FIELD': {
$this->content = (isset($attributes['CONTENT'])) ?
$attributes['CONTENT'] : '';
$this->field = $attributes['NAME'];
}
}
}
function cdata($parser, $cdata) {
$parser;
switch ($this->content) {
case 'base64': {
$this->value = base64_decode($cdata);
} break;
default: {
$this->value = $cdata;
}
}
}
function tag_close($parser, $tag) {
$parser;
switch ($tag) {
case 'DATA': break;
case 'TABLE': break;
case 'ROW': {
$sql = "INSERT INTO $this->table";
$iC=0;
foreach ($this->recordset as $tcaption => $tvalue) {
if ($iC==0) $sql .= "\nSET "; else $sql .= ", ";
$sql .= "
$tcaption = '";
$sql .= mysql_real_escape_string($tvalue,$this->cn);
$sql .= "'";
$iC++;
}
mysql_unbuffered_query($sql,$this->cn);
} break;
case 'FIELD': {
$this->recordset[$this->field] = $this->value;
}
}
}
}
//require('mainfile.php');
require('config.php');
define('XOOPS_DB_HOST', DB_HOST);
define('XOOPS_DB_USER', DB_USUARIO);
define('XOOPS_DB_PASS', DB_SENHA);
define('XOOPS_DB_NAME', 'xoops');
$xsparse = new xmlToDB();
$file = 'bulkinsert.xml';
$fnum = @fopen($file,'r') or exit();//trigger_error('Erro ao abrir o
XML',E_USER_ERROR);
while (($data = fread($fnum,4194304))) {
$xsparse->parse($data);
}
fclose($fnum);
?>
<script>self.close();</script>