I'm using the following code to parse and import an xml feed into my database. The problem is if a field in the XML feed is empty, it comes up with an "Column count doesn't match value count at row 1" Is there something I can insert so that it will just ignore empty fields and import a blank value instead of failing?
Here's the code:
<?php
// initialize some variables
$currentTag = "";
// this array will hold the values for the SQL statement
$values = array();
// this array will hold allowed fields/elements
$allowedFields = array("value1", "value2");
// XML file to parse
$xml_file="file.xml";
// database parameters
$host = "localhost";
$user = "name";
$pass = "pass";
$db = "db";
$table = "table";
// called when parser finds start tag
function startElementHandler($parser, $name, $attributes)
{
global $currentTag;
$currentTag = $name;
}
// called when parser finds end tag
function endElementHandler($parser, $name)
{
global $values, $currentTag;
// import database link and table name
global $connection, $table;
// if ending <item> tag
// implies end of record
if (strtolower($name) == "xmlfield")
{
// generate the query string
$query = "INSERT INTO table ";
$query .= "(value1,value2) ";
$query .= "VALUES(\"" . join("\", \"", $values) . "\");";
// uncomment for debug
// print $query;
// execute query
$result = mysql_query($query);
// reset all internal counters and arrays
$values = array();
$currentTag = "";
}
}
// called when parser finds cdata
function characterDataHandler($parser, $data)
{
global $currentTag, $values, $allowedFields;
// lowercase tag name
$currentTag = strtolower($currentTag);
// look for tag in $allowedFields[] array
// to see if it is to be included in query
if (in_array($currentTag, $allowedFields) && trim($data) != "")
{
// add field=>value pairs to $values array
$values[$currentTag] = mysql_escape_string($data);
}
}
// initialize parser
$xml_parser = xml_parser_create();
// turn off whitespace processing
xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE, TRUE);
// turn on case folding
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, FALSE);
// set callback functions
xml_set_element_handler($xml_parser, "startElementHandler", "endElementHandler");
xml_set_character_data_handler($xml_parser, "characterDataHandler");
// open connection to database
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
mysql_select_db($db) or die ("Unable to select database!");
// read XML file
if (!($fp = fopen($xml_file, "r")))
{
die("File I/O error: $xml_file");
}
// parse XML
while ($data = fread($fp, 4096))
{
// error handler
if (!xml_parse($xml_parser, $data, feof($fp)))
{
$error_code = xml_get_error_code($xml_parser);
die("XML parser error (error code " . $error_code . "): " . xml_error_string($error_code) . "<br>Error occurred at line " . xml_get_current_line_number($xml_parser));
}
}
// all done, clean up!
xml_parser_free($xml_parser);
mysql_close($connection);
?>
Thanks in advance for your help!