【问题标题】:XML into MySql Database (SimpleXML)XML 导入 MySql 数据库 (SimpleXML)
【发布时间】:2017-03-03 13:49:02
【问题描述】:

我从 post 方法中获取了这个 XML 文件:

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

我在我的 POST.php 中使用 $xml = simplexml_load_string($xmlpost); 创建了这个数组:

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

我必须使用 foreach 将 ID、TIME 和 VALUE 放入数据库表 请帮忙 !谢谢!

【问题讨论】:

  • 到目前为止你做了什么?
  • 解析xml数组并将id、时间和值放入db
  • 那是什么问题?
  • 从数组中获取id、时间和数量
  • foreach($xml->attributes() as $attr => $id) { echo $id;}

标签: php mysql arrays xml simplexml


【解决方案1】:

考虑在&lt;misura&gt; 的每个节点位置上使用带有for 循环的SimpleXML 的xpath()

$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

【讨论】:

  • 完美谢谢你这么多冻糕
猜你喜欢
  • 2017-01-11
  • 1970-01-01
  • 2015-05-03
  • 2015-09-23
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 2015-05-21
相关资源
最近更新 更多