1

我无法解析 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代码

$xmlobj = simplexml_load_file("variants.xml");
$variants = $xmlobj->Variants;

foreach ($variants as $item) {
    echo " ".$item->Definition." ";
}
4

2 回答 2

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
        )
)
于 2013-05-07T01:30:21.120 回答
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

于 2013-05-07T10:22:33.960 回答