【问题标题】:simplexml_load_file - foreach shows one time loopsimplexml_load_file - foreach 显示一个时间循环
【发布时间】:2017-09-01 07:49:56
【问题描述】:

我有一个这样的表结构,我需要摆动她的 foreach 循环来提取所有 848 个元素。问题是循环只显示一个项目,而不是坐在那里的实际数量。使用常规 forem 和 idid 替换的方式,虽然在我看来写同样的东西更长更丑。

数组结构:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [language] => pol
            [currency] => PLN
        )

    [product] => Array
        (
            [0] => SimpleXMLElement Object

                [@attributes] => Array
                        (
                            [id] => 8
                        )

            [1] => SimpleXMLElement Object

                [@attributes] => Array
                        (
                            [id] => 4
                        )       

            [etc...]
        )

我试试这个方法

$chairXML = simplexml_load_file('toparser.xml');

        foreach ($chairXML->children() as $children) {

            echo $children->product['id'];

        }

但这不起作用,循环返回一条记录。

【问题讨论】:

  • 如果您包含 XML 文件的副本(或部分)而不是对象结构,则更容易修复。

标签: php xml foreach


【解决方案1】:
$xml = ' 
<xml>
 <product>
   <cherry>1</cherry>
   <apple>3</apple>
   <orange>4</orange>
 </product>
</xml>';
$simpleXmlObj = simplexml_load_string($xml);
foreach ($simpleXmlObj->product->children() as $children) {
    print_r($children);
}

结果

SimpleXMLElement Object
(
    [0] => 1
)
SimpleXMLElement Object
(
    [0] => 3
)
SimpleXMLElement Object
(
    [0] => 4
)

我认为你的问题在 $simpleXmlObj->children() 试试 $simpleXmlObj->product->children()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多