我无法解析XML文件。如何在循环中生成以下代码。 我可以用SimpleXML做到这一点吗?
<Variants>
<Definition>Color=Black</Definition>
<Code/>
<Image>1744.jpg</Image>
<Stock>1</Stock>
<Price>3385.5933</Price>
<CurrencyID>1</CurrencyID>
<Suffix>TL</Suffix>
<Definition>Color=White</Definition>
<Code/>
<Image>1741.jpg</Image>
<Stock>1</Stock>
<Price>3385.5933</Price>
<CurrencyID>1</CurrencyID>
<Suffix>TL</Suffix>
</Variants>
Php Code
$xmlobj = simplexml_load_file("variants.xml");
$variants = $xmlobj->Variants;
foreach ($variants as $item) {
echo " ".$item->Definition." ";
}
答案 0 :(得分:0)
使用print_r($xmlobj)
查看实际的SimpleXML结构并发现可以迭代的位置:
SimpleXMLElement Object
(
[Definition] => Array
(
[0] => Color=Black
[1] => Color=White
)
[Code] => Array
(
[0] => SimpleXMLElement Object
(
)
[1] => SimpleXMLElement Object
(
)
)
[Image] => Array
(
[0] => 1744.jpg
[1] => 1741.jpg
)
[Stock] => Array
(
[0] => 1
[1] => 1
)
[Price] => Array
(
[0] => 3385.5933
[1] => 3385.5933
)
[CurrencyID] => Array
(
[0] => 1
[1] => 1
)
[Suffix] => Array
(
[0] => TL
[1] => TL
)
)
在最简单的情况下,您可以迭代一个属性:
foreach ($xmlobject->Definition as $i=>$item) {
echo " $item ";
}
如果要再次将扩展结构重新转换为组,请使用:
foreach (json_decode(json_encode($xmlobject)) as $key=>$items) {
foreach ($items as $i=>$entry) {
$out["$i"]["$key"] = $entry;
}
}
哪个会给你:
Array
(
[0] => Array
(
[Definition] => Color=Black
[Code] => stdClass Object
(
)
[Image] => 1744.jpg
[Stock] => 1
[Price] => 3385.5933
[CurrencyID] => 1
[Suffix] => TL
)
[1] => Array
(
[Definition] => Color=White
[Code] => stdClass Object
(
)
[Image] => 1741.jpg
[Stock] => 1
[Price] => 3385.5933
[CurrencyID] => 1
[Suffix] => TL
)
)
答案 1 :(得分:0)
您的XML完全有效,请执行以下操作:
$xml = simplexml_load_string($x); // assuming XML in $x
foreach ($xml->Definition as $def) echo "$def<br />";
看到它有效:http://codepad.viper-7.com/7g5nm8
您的代码失败,因为<Variants>
是root并由$xml