Search code examples
phpmysqlxmlsimplexml

insert xml data to mysql with simpleXML


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.


Solution

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