首页 > 解决方案 > 使用 simplexml_load_string 加载 xml 损失数组

问题描述

我想将 xml 导入数据库。当我使用 simplexml_load_string 加载这个 xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <Item title="A">
    <Media type="pic" name="B"/>
    <Media type="pic" name="C"/>
  </Item>
  <Item title="D">
    <Media type="pic" name="E"/>
  </Item>
</data>

$xml = simplexml_load_string($fp);
$json = json_encode($xml, JSON_UNESCAPED_UNICODE);
$array = json_decode($json,TRUE);

Media E当 Item 只有 1 个元素时,这将错过 array[0] 。

                    ...
                    [Media] => Array
                        (
                            [0] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [type] => pic
                                            [name] => B
                                        )

                                )

                            ...


                    [Media] => Array
                        (
                            [@attributes] => Array
                                (
                                    [type] => pic
                                    [name] => E
                                )

                        )

                ...

所以这段代码会导致错误。

foreach ($array['Item'] as $key => $value) {
  $Aarr['title'] = $value['@attributes']['title'];
  //$sql->Insert($table, $Aarr);

  foreach ($value['Media'] as $key2 => $value2) {
    $Barr['name'] = $value2['@attributes']['name'];
    //$sql->Insert($table2, $Barr);  
  }
}

如何让 Media array[0] 开启Media E?谢谢你。

标签: php

解决方案


而不是使用json_encode/ json_decode,您可以自己构建数组,方法是步行将SimpleXMLElement您的 XML 字符串加载到:

$xml     = simplexml_load_string($fp);
$collect = ['Item' => []];

foreach($xml->Item as $item) {

    // Mimic how your original array is build...
    $attributes = (array) $item->attributes();
    $items      = ['@attributes' => $attributes['@attributes'], 'Media' => []];

    foreach ($item->Media as $media) {

        //...but make sure every media item is numerically indexed
        $items['Media'][] = (array) $media->attributes();
    }

    $collect['Item'][] = $items;
}

推荐阅读