用PHP提取XML

Sea*_*hty 0 php xml simplexml

我知道如果XML格式是如何使用simplexml_load_file来获取XML结果

<bowlcontents>
   <banana>yellow</banana>
    <apple>red</apple>
</bowlcontents>
Run Code Online (Sandbox Code Playgroud)

但是,我有一些格式的代码

<bowlcontents>
  <fruit type="banana" skin="yellow" />
  <fruit type="apple" skin="red" />
</bowlcontents>
Run Code Online (Sandbox Code Playgroud)

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

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

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

?>
Run Code Online (Sandbox Code Playgroud)

所以在它的最后我想有一个数组,键=值:

香蕉=黄色

苹果=红

...

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

Jos*_*vis 6

根据PHP的手册,使用数组表示法访问属性:

$bowlcontents->fruit['type'];
Run Code Online (Sandbox Code Playgroud)

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