-
/***
-
* Class retirada do http://php.net
-
* Duvida : mzpiva@gmail.com
-
*/
-
class xml2Array {
-
-
var $arrOutput = array();
-
var $resParser;
-
var $strXmlData;
-
-
function parse($strInputXML) {
-
-
$this->resParser = xml_parser_create ();
-
xml_set_object($this->resParser,$this);
-
xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
-
-
xml_set_character_data_handler($this->resParser, "tagData");
-
-
$this->strXmlData = xml_parse($this->resParser,$strInputXML );
-
if(!$this->strXmlData) {
-
die(sprintf("XML error: %s at line %d",
-
xml_error_string(xml_get_error_code($this->resParser)),
-
xml_get_current_line_number($this->resParser)));
-
}
-
-
xml_parser_free($this->resParser);
-
-
return $this->arrOutput;
-
}
-
function tagOpen($parser, $name, $attrs) {
-
$tag=array("name"=>$name,"attrs"=>$attrs);
-
array_push($this->arrOutput,$tag);
-
}
-
-
function tagData($parser, $tagData) {
-
if(trim($tagData)) {
-
if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
-
$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
-
}
-
else {
-
$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
-
}
-
}
-
}
-
-
function tagClosed($parser, $name) {
-
$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this->arrOutput)-1];
-
array_pop($this->arrOutput);
-
}
-
}
-
-
/***
-
* Abre arquivo XML, sem limite de leitura, adicionando cada linha em uma posição de array.
-
*/
-
$file = file('XML/'.$f_name);
-
-
/***
-
* Converte array em linhas. XML Parse
-
*/
-
foreach ($file as $line) {
-
$xmlParse .= $line;
-
}
-
-
/***
-
* Tranforma XML em Array
-
*/
-
$class = new xml2Array();
-
$arrayXml = $class->parse($xmlParse);
-
-
/***
-
* Captura Campos e Valores para query de Insert e adiciona ao array.
-
*/
-
foreach ($arrayXml[0] as $arrayChildren) {
-
if (is_array($arrayChildren)) {
-
$s = 0;
-
foreach ($arrayChildren as $values) {
-
$i = 0;
-
foreach ($values['children'] as $children) {
-
$sql[$s][$i]['i'] = $children['name']; // Campos
-
$sql[$s][$i]['v'] = $children['tagData']; // Valores
-
$i++;
-
}
-
$s++;
-
}
-
}
-
}
-
-
/***
-
* Monta Querys para Insert.
-
*/
-
foreach ($sql as $record) {
-
-
// Campos
-
$i = 0;
-
foreach ($record as $value) {
-
$arrayInsert[$i] = $value['i'];
-
$i++;
-
}
-
-
// Valores
-
$i = 0;
-
foreach ($record as $value) {
-
$arrayValues[$i] = $value['v'];
-
$i++;
-
}
-
-
// Exibe Querys
-
$query= 'INSERT INTO tabela_x (' . implode(', ', $arrayInsert) . ') VALUES (\'' . implode('\', \'', $arrayValues) . '\')';
-
$res = mysql_query($query) or die ("Error in query: $query. " .mysql_error());
-
-
// print "\r\n";
-
}