0

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.

1
  • Do (string)$item instead of $item["value"] Commented Mar 30, 2017 at 14:58

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting an empty array.
Even better, wish i could upvote 5x :) Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.