Search code examples
phpnestedparsexml

PHP - parse xml to nested json


I am trying to parse a xml to a nested json structure with php.

This is my test script:

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

I get a structure like that:

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

But I dont want the keys "id" and "name" to be nested. It should look like this:

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

How can I handle that?


Solution

  • Assuming your JSON's "drive" objects will always have this structure:

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

    You can use:

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