仅获取第一个元素的子元素

时间:2017-02-25 15:47:15

标签: php xml simplexml

我的XML文件就像(例如):

<?xml version="1.0" encoding="UTF-8" ?>
<bikes>
    <bike>
        <model>First</model>
        <speedNumber>4</speedNumber>
        <sizes>100</sizes>
        <amount>100</amount>
    </bike>
    <bike>
        <model>Second</model>
        <speedNumber>3</speedNumber>
        <sizes>300</sizes>
        <amount>150</amount>
    </bike>
    <bike>
        <model>Third</model>
        <speedNumber>4</speedNumber>
        <sizes>300</sizes>
        <amount>300</amount>
    </bike>
</bikes>

如何才能获取第一个<bike>元素的子元素?
我想打印model=FirstspeedNumber=4 ...

<bike>
  <model>First</model>
  <speedNumber>4</speedNumber>
  <sizes>100</sizes>
  <amount>100</amount>
</bike>

我试过了:

foreach ($xml->children(0) as $bikes) 
{
  foreach ($bikes->children() as $childs)
  {
    echo $childs->getName()."=".$childs ." ";
  }
  echo "<br>";
}

但它对我不起作用。
我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用数组语法直接访问元素:

$bikes->bike[0]->model
$bikes->bike[0]->speedNumber
...

完整代码:

<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<bikes>
    <bike>
        <model>First</model>
        <speedNumber>4</speedNumber>
        <sizes>100</sizes>
        <amount>100</amount>
    </bike>
    <bike>
        <model>Second</model>
        <speedNumber>3</speedNumber>
        <sizes>300</sizes>
        <amount>150</amount>
    </bike>
    <bike>
        <model>Third</model>
        <speedNumber>4</speedNumber>
        <sizes>300</sizes>
        <amount>300</amount>
    </bike>
</bikes>
XML;

$bikes = new SimpleXMLElement($xml);

echo $bikes->bike[0]->model . "\n";
echo $bikes->bike[0]->speedNumber . "\n";
echo $bikes->bike[0]->sizes . "\n";
echo $bikes->bike[0]->amount . "\n";

?>

在这里测试:http://codepad.org/yVAyoPtG