Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.