With the code below I import my XML file to mySQL with the limitation that the elements of my XML have to have the same name and order with the fields in the DB. Ok with the same names but I have problem with the order of them because I handle many XMLs with different order.
My question is how can I edit my existing code so that I will have the possibility to assign the values to the fields like $product->name, $product->id and so on? My difficulty is because it uses array.
This is my DB structure id, name, description, price, image, url, category, category_id, shopid but some of my XMLs are not in that order.
Thank you.
$xml = simplexml_load_file('test.xml');
foreach($xml->product as $product)
{
$columns = array();
$data = array();
foreach($product->children() as $child)
{
$columns[] = $child->getName();
$data[] = mysql_real_escape_string((string)$child);
}
$col = '`'. implode('`,`',$columns) .'`';
$val = '"'. implode('","',$data).'"';
$query = "INSERT INTO products ($col) VALUES ($val)";
mysql_query($query);
}
What you want to do is serialize the xml into an object so then you can access the product as an object for example $product->Id. You’d do well to read about that here: http://www.devshed.com/c/a/PHP/Serializing-XML-With-PHP/ (all the steps). Then use a prepared statement using PDO (Part of PHP) to run the sql. Read more about why using PDO is better and how to get it working here: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Be happy to help you understand any of the information in either of those two links.