Jump to content

simple xml file to be INSERTED into MYSQL db?


phpnewby1918

Recommended Posts

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  :)

 

 

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);
?> 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.