PHP - 将 xml 解析为嵌套的 json

PHP - parse xml to nested json

我正在尝试将 xml 解析为具有 php 的嵌套 json 结构。

这是我的测试脚本:

$json_drives = array();

foreach($drives->DR as $dr){
    $current_drive = array();
    $current_drive['id'] = $dr->ID;
    $current_drive['name'] = $dr->NAME->D;
    $json_drives[] = $current_drive;
}
echo("Finished");

// Parse and save
$f = json_encode($json_drives);
file_put_contents('test12345.json', $f);

我得到这样的结构:

[
    {
        "id": {
            "0": "1"
        },
        "name": {
            "0": "Name 1"
        }
    },
    {
        "id": {
            "0": "2"
        },
        "name": {
            "0": "Name 2"
        }
    },
    // ...
 ]

但我不想嵌套键 "id" 和 "name"。它应该是这样的:

[
    {
        "id": "1"
        "name": "Name 1"
    },
    {
        "id": "2"
        "name": "Name 2"
    },
    // ...
]

我该如何处理?

假设您的 JSON 的 "drive" 对象将始终具有此结构:

"id": {
    "0": "Some ID"
},
"name": {
    "0": "Some name"
}

您可以使用:

$current_drive['id'] = ((array) $dr->ID)[0];
$current_drive['name'] = ((array) $dr->NAME->D)[0];