insert xml data to mysql with simpleXML

醉酒当歌 提交于 2020-01-04 14:32:32

问题


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')

Problem is that i dont know how to create foreach for this.


回答1:


Just use SimpleXML, access the values and just do a normal foreach along with your insertion codes (either MySQLi or PDO).

Example Code:

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


来源:https://stackoverflow.com/questions/25564070/insert-xml-data-to-mysql-with-simplexml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!