phpnewby1918 Posted April 27, 2010 Share Posted April 27, 2010 HI i've been looking over this for a few days and its blagging my head in adn wondered if anyone could help me. I've been using this xml from w3schools: <?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Dont forget me this weekend!</body> </note> and used this script to display the data: <?php $xml = simplexml_load_file("test.xml"); echo $xml->getName() . "<br />"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br />"; } ?> This is all very good and i follow it fine. But the trouble i'm having is how to put this data into my mysql db. I've set up a mysql table with these columns: id (Auto increment) to from heading body Unfortunately all i've managed to do so far is get each $child put into every column 4 times aka id to from heading body 1 Tove Tove Tove Tove etc etc etc etc etc I've read actually quite alot around it but i couldnt find anything that i could pick up particulary easily, including php.net. So i wondered if someone may be able to show me how i can insert that simple xml file into my database. I was hoping to get this in my database: id to from heading body 1 Tove Jani Reminder Dont forget me this weekend! I realise this may be a silly question, but i have really tried to do it for like 5 days now and i keep making a mess of it. Thanks in Advance Quote Link to comment https://forums.phpfreaks.com/topic/199977-simple-xml-file-to-be-inserted-into-mysql-db/ Share on other sites More sharing options...
PFMaBiSmAd Posted April 27, 2010 Share Posted April 27, 2010 One of the possible ways - <?php // your db connection and selection code ... $columns = array(); $data = array(); $xml = simplexml_load_file("test.xml"); echo $xml->getName() . "<br />"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br />"; $columns[] = $child->getName(); $data[] = (string)$child; } $col = '`'. implode('`,`',$columns) .'`'; $val = "'". implode("','",$data)."'"; $query = "INSERT INTO your_table ($col) VALUES ($val)"; echo $query; mysql_query($query); ?> Quote Link to comment https://forums.phpfreaks.com/topic/199977-simple-xml-file-to-be-inserted-into-mysql-db/#findComment-1049606 Share on other sites More sharing options...
phpnewby1918 Posted April 27, 2010 Author Share Posted April 27, 2010 Wow, Thank you very much. I don't think i'd ever have been able to come to that soultion on my own. But i'm really greatful for you showing me how. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/199977-simple-xml-file-to-be-inserted-into-mysql-db/#findComment-1049618 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.