g5wx
g5wx

Reputation: 720

Parsing XML file and coverting it to array of objects

I'm trying to get the XML contents and organize it as objects to retreive them in json file.

XML structure:

<lorem date="2017-01-01">
    <ipsum key="a">0001</ipsum>
    <ipsum key="b">0002</ipsum>
    <ipsum key="c">0003</ipsum>
    <ipsum key="d">0004</ipsum>
</lorem>

and PHP

<?php
    $URL = simplexml_load_file("http://www.example.com");
    foreach($URL -> lorem -> ipsum as $item){
        $arr = array($item["key"] => $item["value"]);
    }
    echo json_encode($arr);
?>

At the end i would like to get json returned with the following structure:

{
"a": "0001",
"b": "0002",
"c": "0003",
"d": "0004",
}

But i'm stuck on how to retrieve values between the ipsum tags. And also the code above doesn't work as expected.

Upvotes: 0

Views: 54

Answers (1)

JustOnUnderMillions
JustOnUnderMillions

Reputation: 3795

Change your code like this

<?php
    $URL = simplexml_load_file("http://www.example.com");
    foreach($URL->ipsum as $item){
        $arr[] = array((string)$item["key"] => (string)$item);
    }
    echo json_encode($arr);


    //for the format you show above
    $URL = simplexml_load_file("http://www.example.com");
    $arr = new stdClass();
    foreach($URL->ipsum as $item){
        $key = (string)$item["key"];
        $arr->{$key} = (string)$item;
    }
    echo json_encode([$arr]);
?>
  • via (string)$item["key"] you access always a node attribute
  • via $item->subnode you get the child node(s)
  • via (string)$item you get the content of the current node

Upvotes: 1

Related Questions