tags:

views:

63

answers:

1

I know how to use simplexml_load_file to get XML results if the XML format is

<bowlcontents>
   <banana>yellow</banana>
    <apple>red</apple>
</bowlcontents>

However, I have some code that is in the format

<bowlcontents>
  <fruit type="banana" skin="yellow" />
  <fruit type="apple" skin="red" />
</bowlcontents>

and I want to manipulate it in the same way as in the first example. How would I do this?

EDIT: This is precisely what I want to do, yet the code below doesn't work.

<?php
$url = "http://worldsfirstfruitAPI.com/fruit.xml";

    $xml = (simplexml_load_file($url));


    $results = array();
    foreach ($xml->bowlcontents->fruit as $fruit) {
        $results[] = array(
            $fruit['type'] => $fruit['skin'],
            );
    }
    return $results;
}

?>

So at the end of it I would like to have an array, key=value:

banana=yellow

apple=red

...

I hope this clarifies. Thanks!

+6  A: 

As per PHP's manual, attributes are accessed using the array notation:

$bowlcontents->fruit['type'];

Come to think of it, you didn't say in your question what was your problem. If that's about iterating over nodes, you can do it using foreach.

/*
$bowlcontents = simplexml_load_string(
    '<bowlcontents>
      <fruit type="banana" skin="yellow" />
      <fruit type="apple" skin="red" />
    </bowlcontents>'
);
*/

$url = "http://worldsfirstfruitAPI.com/fruit.xml";
$bowlcontents = simplexml_load_file($url);

foreach ($bowlcontents->fruit as $fruit)
{
    echo $fruit['type'], "'s skin is ", $fruit['skin'], "<br/>\n";
}
Josh Davis
Hi - thanks very much for your reply. I have edited my original question to clarify what I mean, I would be grateful if you could help accordingly. Cheers.
Sean McRaghty
The answer is really the same. The root node of that XML document is `<bowlcontents/>` therefore the PHP variable should be `$bowlcontents` to avoid any confusion. `<bowlcontents/>` is not a child, it *is* `$bowlcontents`.
Josh Davis
Hi - thanks for your reply. I don't want to echo "banana's skin is yellow", I want to load the extracted info into an array called `$results`. I thought that the updated code in my question would do this, but it doesn't seem to work? I've also just realised that my XML will actually have 'query' wrapped around 'bowlcontents', so bowlcontents will be a child of query. Thanks!
Sean McRaghty