【问题标题】:insert xml into mysql将xml插入mysql
【发布时间】:2020-07-13 02:14:31
【问题描述】:

您好,我尝试将 xml 文件中的一些数据插入 mysql,我需要将数据代码插入参考列和数量列中的数据 qta XML 是:

<dispo>

<codice>CA031BL</codice>

<arrivi>

  <arrivo>

    <maga>B</maga>

    <data>2020-04-01</data>

    <qta>0</qta>

  </arrivo>

</arrivi>

<codice>CA031BL</codice>

<arrivi>

  <arrivo>

    <data>2020-04-01</data>

    <maga>C</maga>

    <qta>30</qta>

  </arrivo>
  </dispo>

在 php 文件中我插入了这个: 连接到 mysql 数据库工作 simplexml 加载似乎工作 如果我在 $quantity 和 $reference 中插入数字,它可以工作,但我如何插入 xml 文件的右列?

<?php
$conn = mysqli_connect("host", "user", "psw", "db");

$affectedRow = 0;

$xml = simplexml_load_file("http://......./dispo2.xml") or die("Error: Cannot create object");

foreach ($xml->children() as $row) {
    $quantity = $row->qta;
    $reference = $row->codice;

    $sql = "UPDATE ps_stock_available set quantity = '$quantity' where id_product = (SELECT id_product from ps_product where reference in ('$reference')";

    $result = mysqli_query($conn, $sql);

    if (! empty($result)) {
        $affectedRow ++;
    } else {
        $error_message = mysqli_error($conn) . "\n";
    }
}
?>
<h2>Insert XML Data to MySql Table Output</h2>
<?php
if ($affectedRow > 0) {
    $message = $affectedRow . " records inserted";
} else {
    $message = "No records inserted";
}

?>
<style>
body {  
    max-width:550px;
    font-family: Arial;
}
.affected-row {
    background: #cae4ca;
    padding: 10px;
    margin-bottom: 20px;
    border: #bdd6bd 1px solid;
    border-radius: 2px;
    color: #6e716e;
}
.error-message {
    background: #eac0c0;
    padding: 10px;
    margin-bottom: 20px;
    border: #dab2b2 1px solid;
    border-radius: 2px;
    color: #5d5b5b;
}
</style>
<div class="affected-row"><?php  echo $message; ?></div>
<?php if (! empty($error_message)) { ?>
<div class="error-message"><?php echo nl2br($error_message); ?></div>
<?php } ?>

我还需要在导入数据之前插入这个,因为我必须使用相同的代码在 mysql 的数量中插入我的 xml 的值 qta 的总和:

 select `reference`, sum(`quantity`)
    from `ps_product_attribute`
    group by `reference`

【问题讨论】:

  • 你检查dev.mysql.com/doc/refman/8.0/en/xml-functions.html了吗?你使用 MySQL 8 还是 5?我还建议您从示例中删除所有非必要的代码,尤其是 CSS,这样可以更轻松地阅读您的问题。
  • 该代码的确切问题是什么?为什么要使用SELECT 查询插入数据?

标签: php mysql xml


【解决方案1】:

从 SimpleXML 加载数据并仅使用时

$quantity = $row->qta;

数量的值将是一个 SimpleXMLElement,您可以使用它来检查

var_dump($quantity);

会显示

class SimpleXMLElement#6 (0) {
}

因此,如果您想在大多数其他情况下使用这些值,那么您可能需要将它们转换为字符串...

$quantity = (string)$row->qta;

这个问题可以隐藏起来,因为像 echo 这样的东西会自动将值转换为字符串以输出它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多