开发者

Parsing data (PHP, MySQL)

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.


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
}


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


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();
    }
}


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜