使用simpleXML将xml数据插入mysql [英] insert xml data to mysql with simpleXML
本文介绍了使用simpleXML将xml数据插入mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须将数据从xml插入数据库,但是我对这个特定数据有疑问
I have to insert data from xml to database, but i have a problem with this specific data
<specifications>
<attribute_group name="attributeGroup1">
<attribute name="attribute1">
<value>value1</value>
</attribute>
<attribute name="attribute2">
<value>value2</value>
</attribute>
<attribute name="attribute3">
<value>value3</value>
</attribute>
</attribute_group>
<specifications>
我需要在数据库中插入类似的内容
I need to insert into database something like
INSERT INTO specs (attr_group,attr_name, attr_value) VALUES ('$attr_group','$attr_name', '$attr_value')
问题是我不知道如何为此创建foreach.
Problem is that i dont know how to create foreach for this.
推荐答案
只需使用SimpleXML
,访问值,并与插入代码(MySQLi或PDO)一起进行常规的foreach操作即可.
Just use SimpleXML
, access the values and just do a normal foreach along with your insertion codes (either MySQLi or PDO).
示例代码:
$db = new mysqli('localhost', 'username', 'password', 'database');
$xml = simplexml_load_string($xml_string); // or load file
$insert = $db->prepare('INSERT INTO specs (attr_group,attr_name, attr_value) VALUES (?, ?, ?)');
foreach($xml as $group) {
$attribute_group = (string) $group->attributes()['name'];
foreach($group as $attr) {
$attribute = (string) $attr->attributes()['name'];
$value = (string) $attr->value;
$insert->bind_param('sss', $attribute_group, $attribute, $value);
$insert->execute();
}
}
这篇关于使用simpleXML将xml数据插入mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文