0

I have to write the values of the XML elements to the MySQL database. For example, let's say, I have this XML document:

<users>
    <user>
        <name>John</name>
        <nick>nick1</nick>
    </user>
    <user>
        <name>Jack</name>
        <nick>nick2</nick>
    </user>
    <user>
        <name>Mike</name>
        <nick>nick3</nick>
    </user>
</users>

And I have to write the values to the members table in MySQL database. So, the members table must be like this:

+------+----------+
| name |  nick    |
+----+------------+
| John |  nick1   |
+------+----------+
| Jack |  nick2   |
+------+----------+
| Mike |  nick3   |
+------+----------+

And I want to do this process in PHP. If you have any idea, please comment.

John
  • 877
  • 5
  • 14
  • 21

3 Answers3

1
$xmlString="<users>
    <user>
        <name>John</name>
        <nick>nick1</nick>
    </user>
    <user>
        <name>Jack</name>
        <nick>nick2</nick>
    </user>
    <user>
        <name>Mike</name>
        <nick>nick3</nick>
    </user>
</users>
";

$xml=new SimpleXMLIterator($xmlString);
foreach($xml as $user){
    $name=$user->name;
    $nick=$user->nick;
    mysql_query("INSERT INTO members(name, nick) VALUES('$name', '$nick')");
}

The important part of the code is new SimpleXMLIterator($xmlString), this will create an object that you can loop over.

Runs fine, tested.

Drahcir
  • 11,772
  • 24
  • 86
  • 128
0

To get data from xml documents you must parse the document first. There are a number of php xml parsers. THey provide an interface in which to access the data from the xml document.

dm03514
  • 54,664
  • 18
  • 108
  • 145
0

Use an XML parser to load the contents of the XML data onto a php object (most likely stdClass).

The loop through the results and perform each insert.

Community
  • 1
  • 1
0x6A75616E
  • 4,696
  • 2
  • 33
  • 57