用PHP提取XML

时间:2010-02-17 21:00:45

标签: php xml simplexml

我知道如果XML格式是

,如何使用simplexml_load_file来获取XML结果
<bowlcontents>
   <banana>yellow</banana>
    <apple>red</apple>
</bowlcontents>

但是,我有一些格式为

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

我想以与第一个例子相同的方式操纵它。我该怎么做?

编辑:这正是我想要做的,但下面的代码不起作用。

<?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;
}

?>

所以最后我想要一个数组,key = value:

香蕉=黄色

苹果=红色

...

我希望这澄清一下。谢谢!

1 个答案:

答案 0 :(得分:6)

根据PHP's manual,使用数组表示法访问属性:

$bowlcontents->fruit['type'];

想想看,你没有在你的问题中说出你的问题是什么。如果这是关于迭代节点,您可以使用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";
}