开发者

Extracting XML with PHP

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

<开发者_StackOverflow社区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!


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";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜