如何使用php SimpleXML打印xml元素及其子元素的名称/值?

时间:2017-02-25 14:10:10

标签: php xml dom 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>

我使用SimpleXML阅读它。 如何打印所有标签的信息,例如

bike: model=First , speedNumber=4 ..

我的代码:

$xml=simplexml_load_file("bike.xml") or die('Cannot load file');
foreach($xml->children() as $bikes) {
    echo $bikes->getName()." : ";
    echo $bikes->model . " ";
    echo $bikes->speedNumber . " ";
    echo $bikes->sizes . "";
    echo $bikes->amount . "<br>";
}

现在我打印自行车:

First 4 100 100 bike: Second 3 300 150 

如何打印

bike: model=First speedNumber=4 ...

1 个答案:

答案 0 :(得分:2)

使用$bikes选择$bikes->children()的孩子并循环播放。在foreach循环中,生成目标字符串。

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

请参阅demo

中的结果