【问题标题】:PHP Foreach loop with a single array to MySQL from XMLPHP Foreach 循环从 XML 到 MySQL 的单个数组
【发布时间】:2018-08-01 15:43:41
【问题描述】:

我从 xml 文件开始,输入如下:

<?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>

将 PHP 与 xml2Array 函数一起使用,我得到以下数组:

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

我用 foreach 读取了这个结果,并将这 2 条记录插入到 MySql 中。 现在的问题是:这仅适用于 xml (>2) 中的多个记录。如果我在 xml 中只有一条记录,则数组如下所示,并且没有插入任何行。你能建议我该怎么做吗?

似乎这个具有单个条目的数组具有不同的形式。我希望这不是原因 非常感谢!

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

Foreach 是这样的:

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

【问题讨论】:

  • "带有 xml2Array 函数" 什么 xml2Array 函数?没有原生的PHPxml2Array()函数。
  • 不是原生的,是的。但可以添加以将 xml 转换为 phph 数组。谢谢!

标签: php mysql xml foreach


【解决方案1】:

您的xml2Array 函数将单个记录与记录列表区别对待,在第二种情况下添加了一个额外的维度。你需要特别对待第一种情况。

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

那么您的循环将适用于这两种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 2011-06-09
    • 2020-05-17
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多