Code this ugly should be illegal. It does what it says, though.
I'd add some sample data, but this is just too far in my past. The original data was just an xml file with tags going two levels deep.
<?php
if (! ($xmlparser = xml_parser_create()) )
{
die ("Cannot create parser");
}
xml_set_element_handler($xmlparser, "start_tag", "end_tag");
xml_set_character_data_handler($xmlparser, "tag_contents");
$filename = "Rates.xml";
$current = "";
$values = array();
$fieldsToInclude = array( 'PUT', 'TAGS', 'TO', 'PUT', 'IN', 'DB', 'HERE' );
$endingTag = 'TTS'; // this is the tag that triggers the creation of the query
if (!($fp = fopen($filename, "r"))) { die("cannot open ".$filename); }
while ($data = fread($fp, 4096)){
$data=eregi_replace(">"."[[:space:]]+"."< ",">< ",$data);
if (!xml_parse($xmlparser, $data, feof($fp))) {
$reason = xml_error_string(xml_get_error_code($xmlparser));
$reason .= xml_get_current_line_number($xmlparser);
die($reason);
}
}
xml_parser_free($xmlparser);
function start_tag($xmlparser, $name, $attribs) {
global $current;
$current = $name;
}
function end_tag($xmlparser, $name) {
// after the last end-tag, write out the query:
global $values;
global $current;
global $endingTag;
$current = ''; // clear out the current tag
if ($name==$endingTag)
{
reset($values);
$ks = $vs = '';
foreach($values as $key=>$value)
{
$value = addslashes($value);
$vs .= "'$value',";
$ks .= strtolower($key).',';
}
$vs = rtrim($vs,',');
$ks = rtrim($ks,',');
$q = 'INSERT INTO table ('.$ks.') VALUES ('.$vs.')';
insert_query($q); /////// you need to define this
$values = array();
}
}
function tag_contents($xmlparser, $data) {
global $current;
global $values;
global $fieldsToInclude;
if (in_array($current, $fieldsToInclude))
{
$values[$current] = $data;
}
}
//// redefine this to insert the row
function insert_query($q) { echo "$q"; }