2017-02-25 47 views
1

我有XML:如何使用php SimpleXML打印xml元素的名稱/值和childs?

<?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 ... 

回答

2

選擇的孩子使用$bikes->children()並通過它們循環。在foreach循環中,生成目標字符串。

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

參見導致demo

相關問題