Search code examples
phpmysqlarraysxmlsimplexml

XML into MySql Database (SimpleXML)


I've this XML file taked from post method :

<?xml version="1.0" encoding="utf-8"?>
<impianto id="id1">
  <misure>
    <misura time="1900-01-01T01:01:01+01:00" quantita="1"/>
    <misura time="0001-01-01T00:00:00+01:00" quantita="-79228162514264337593543950335"/>
    <misura time="9999-12-31T23:59:59.9999999+01:00" quantita="79228162514264337593543950335"/>
  </misure>
</impianto>

I've create with $xml = simplexml_load_string($xmlpost); in my POST.php this array :

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => id1
        )

    [misure] => SimpleXMLElement Object
        (
            [misura] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [time] => 2016-01-01T01:01:01
                                    [quantita] => 1234
                                )    
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [time] => 2016-01-01T01:01:01
                                    [quantita] => 3456
                                )    
                        )    
                )    
        )    
)

And i have to put ID, TIME , AND VALUE in to Database Table with foreach Please Help ! Thank You !


Solution

  • Consider using SimpleXML's xpath() with a for loop on each node position of <misura>:

    $xml = simplexml_load_string($xmlpost);
    
    $count = count($xml->xpath('//misura'));
    
    for($i = 1; $i <= $count; $i++){
        $id = $xml->xpath('/impianto/@id')[0];
        $qty = $xml->xpath('//misura['.$i.']/@time')[0];
        $value = $xml->xpath('//misura['.$i.']/@quantita')[0];
    
        echo $id.' '.$qty.' '.$value."\n";          // PASS VALUES INO MYSQL
    }
    
    # id1 1900-01-01T01:01:01+01:00 1
    # id1 0001-01-01T00:00:00+01:00 -79228162514264337593543950335
    # id1 9999-12-31T23:59:59.9999999+01:00 79228162514264337593543950335