tags:

views:

106

answers:

5

Hi guys!

I have a file with data in the following format:

<user>
    <fname>Anthony</fname>
    <lname>Smith</lname>
    <accid>3874918</accid>
</user>

<user>
     ...
</user>

I'm trying to parse this data and store it to MySQL database with the follwing fields: fname, lname, accid.

Now the problem is how to determine <user> and </user> so I can parse the data inside of it? Thank you.

+1  A: 

If it is an xml file, I would suggest using an XML parser (this ?) instead of playing with regular expressions and/or string functions.

shylent
+1  A: 

You should to this using a dom parser(or xml parser, depending on your data). It would look something like this (warning: untested code):

$dom = new DOMDocument();
$dom->loadXML($xmlString); 
$list = $dom->getElementsByTagName('user');
for ($i = 0; $i < $list->length; $i++) {
    $userNode = $list->item($i);
    $node = $userNode->firstChild();
    while ($node !== NULL) {
        switch ($node->$nodeName) {
            case 'fname':
                // ...
        }
        $node = $node->nextSibling();
    }
}
soulmerge
+4  A: 

If it's valid XML, use SimpleXML. First you will need to ensure that you have a single root element, for example <users>:

<?php
$str = "<users>
            <user>...</user>
            <user>...</user>
        </users>";

$xml = simplexml_load_string($str>;
foreach ($xml as $user) {
    // Make a query using $user->fname, $user->lname, $user->accid
}
Ben James
It is not valid XML, if it does not contain a single root node.
soulmerge
Yes, this is true. I was not sure if he had posted only an extract, or a true representation of the document structure.
Ben James
+1  A: 

Assuming you're using php5 (you should be) you could create a simpleXML object and use it and PDO to do it, with very little code. Using mysql_ functions and parsing the XML by hand would take a lot more code.

Here is an example:

$names = simplexml_load_file('names.xml');

foreach ($names->user as $user) { 

$pdo->exec("INSERT INTO names (fname, lname, accid)" . " VALUES ('" . $user->fname . " ', '" . $user->lname . "','" . $user->accid . "')")
or die("failed insert");

}

This isn't tested code, but it gives you a good idea of how it works. For a production app I would want to put some more error checking and validation in it, but this should get you started.

Jeremy Morgan
+1  A: 

Hi. If you are using PHP5.x, SimpleXML will help you.

<?php
$sample = <<<END                                                                                                             
<foo>
 <user>
    <fname>Anthony</fname>
    <lname>Smith</lname>
    <accid>3874918</accid>
  </user>
  <user>
    <fname>foo</fname>
    <lname>bar</lname>
    <accid>123</accid>
  </user>
</foo>
END;

$xml = simplexml_load_string($sample);
var_dump($xml);
yinkyweb