解析xml文件并插入mysql数据库 [英] Parse xml-file and insert into mysql database

查看:158
本文介绍了解析xml文件并插入mysql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析xml文件并将其插入mysql数据库. xml文件(syntest.xml)如下所示:

I'm trying parse an xml file and insert it into an mysql database. The xml file (syntest.xml) looks like this:

<synonyms>
<syn level="4.0"><w1>LP</w1><w2>vinylskiva</w2></syn>
<syn level="3.7"><w1>OK</w1><w2>javisst</w2></syn>
<syn level="4.6"><w1>OS</w1><w2>operativsystem</w2></syn>
</synonyms> 

我已经使用simplexml_load_file解析了xml文件,并且当我使用foreach循环在浏览器中打印记录时,该循环遍历了所有记录,并且一切正常.但是,当我尝试将数据插入数据库时​​,循环不会迭代,仅插入一条记录.

I have parsed the xml file using simplexml_load_file, and when I use an foreach loop to print the records in the browser the loop goes through all records and everyting looks fine. But when I try to insert the data into the database, the loop doesnt iterate and only one record is inserted.

代码如下:

<?php

$con = mysql_connect("localhost","user","username");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("db_name", $con);


if(!$xml=simplexml_load_file('syntest.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}



foreach ($xml as $syn) {
$w1 = $syn->w1;  
$w2 = $syn->w2;     
}

$sql="INSERT INTO db_name (w2, w1)
VALUES
('$w1','$w2')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Records added";

mysql_close($con)
?>    

非常感谢所有帮助!

推荐答案

mysql_query的位置不正确.您必须在循环中插入记录:

The place of mysql_query isn`t correct. You must insert records in loop:

foreach ($xml as $syn) 
{
    $w1 = $syn->w1;  
    $w2 = $syn->w2;  

    $sql    = "INSERT INTO db_name (w1, w2) VALUES ('$w1','$w2')";
    $query  = mysql_query($sql);

    if (!$query)
    {
        echo ('Error: ' . mysql_error());
    }
    else 
    {
        echo "Record added";
    }
}
mysql_close($con);

这篇关于解析xml文件并插入mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆