php - 使用 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
?谢谢你。
解决方案
而不是使用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;
}
推荐阅读
- javascript - sessionStorage 数据存储在哪里?
- apache-nifi - Apache Nifi - 将大型 Json 文件拆分为具有指定记录数的多个文件
- django - Django formtools,如何设置wizard_view cookie过期日期?
- h2o - 在 H2o 苏打水中运行具有 300 列(6 GB)的大型数据集的 coxph 模型
- c++ - 在这种情况下,为什么不调用我的虚函数实现?
- apollo - 使用 Apollo GraphQL 在 Next.js 应用程序上进行虚拟托管
- python-3.x - 如何将日期作为查询传递给 Python 中 Microsoft O365 日历中的 get_events()
- php - 我应该使用 Get 或 Delete 方法删除 laravel 中的记录吗?
- google-apps-script - 为什么我收到此错误“无法绘制图表:未指定数据。”?
- passwords - 生成注册密码导致 404 错误