简体   繁体   中英

PHP Foreach loop with a single array to MySQL from XML

I start from xml file with following input:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<severa>
<mesaj id="6caca93f" tip="ATENTIONARE"cod="GALBEN"" />
<mesaj id="6caca93g" tip="ATENTIONARE" cod="GALBEN"  />
</severa>

Using PHP with xml2Array function I obtain below array:

Array
(
[0] => Array
(
[@attributes] => Array
(
[id] => 6caca93f
[tip] => ATENTIONARE
[cod] => GALBEN
)
)
[1] => Array
(
[@attributes] => Array
(
[id] => 6caca93g
[tip] => ATENTIONARE
[cod] => GALBEN
)
)
)

I read this result with foreach and insert this 2 records into MySql. Now the problem: this works only for multiple records in xml (>2). If I have only one record in xml the array look like below and no row is inserted. Could you please advice what I should do?

Seems that this array with a single entry have a different form. I hope this is not the reason Thank you so much!

    Array
(
[@attributes] => Array
(
[id] => 6caca93f
[tip] => ATENTIONARE
[cod] => GALBEN
)
)

Foreach is like this:

foreach ($a as $row) {
        $atributes = $row['@attributes'];
        $id = $atributes['id'];
        $tip = $atributes['tip'];
        $cod = $atributes['cod'];
        mysqli_stmt_execute($st);
    }

Your xml2Array function is treating a single record differently from a list of records, adding an extra dimension in the second case. You need to treat the first case specially.

if (isset($a['@attributes'])) { // Single record, turn it into an array
    $a = array($a);
}

Then your loop will work for both cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM