大佬教程收集整理的这篇文章主要介绍了使用 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);
当 Item 只有 1 个元素时,这将错过 @H_232_5@media E 上的 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);
}
}
如何在 @H_232_5@media E 上拥有 Media array[0]? 谢谢。
您可以不使用 json_encode
/json_decode
,而是通过遍历要加载 XML 字符串的 SimpleXMLElement
自行构建数组:
$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;
}
以上是大佬教程为你收集整理的使用 simplexml_load_string 加载 xml 损失数组全部内容,希望文章能够帮你解决使用 simplexml_load_string 加载 xml 损失数组所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。