【问题标题】:PHP Accessing SimpleXMLElement Object array keysPHP 访问 SimpleXMLElement 对象数组键
【发布时间】:2012-02-03 04:08:36
【问题描述】:

在下面的 SimpleXMLElement Object $results 中,我想从 TEST 数组中删除 ID 为 13011146 的元素。我不确定如何正确访问值为1 的数组键,所以我使用了计数器$i,但这给了我一个错误Node no longer exists,指向foreach 行。

TL;DR:你如何取消$result->TEST[1] 的设置?

SimpleXMLElement Object
(
    [TEST] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [ID] => 13011145
                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [ID] => 13011146
                        )

                )
        )

)

PHP:

$i = 0;
foreach($results->TEST as $key => $value) {
    if( (string)$value['ID'] == 13011146 ) {
        unset($results->TEST[$i]);
    }
    $i++;
}

【问题讨论】:

  • 您能否提供XML 为主要SimpleXMLElement Object

标签: php simplexml


【解决方案1】:

试试这个

$node = $results->children();
unset($node[1]);

【讨论】:

    【解决方案2】:
    foreach($results->TEST->children() as $key => $value) { 
        $attributes = $value->attributes();
        foreach($attributes as $a => $b) {
            if (( (string)$a == 'ID' ) && ( (string)$b == '13011146' )) {    
                unset($results->TEST[$key]);    
            }
        }
    }
    

    【讨论】:

    • 抱歉,误读了您的结构:应该通过调用 children() 来修复 - 请参阅编辑后的版本
    • 现在我们甚至没有进入第一个 foreach 循环:s 如果我删除 children(),那么如果找到 $a 和 $b 的匹配项,但 $key 的值又是错误的。
    【解决方案3】:

    更优雅的方式;它在不使用 $attributes[ '@attributes' ] 的情况下为您提供相同的结果:

    $attributes = current($element->attributes());
    

    对于特定的键/值对,我们可以使用like:

    $attributes = current($value->attributes()->NAME);
    

    希望对你有帮助!

    【讨论】:

      【解决方案4】:

      试试这个:

         $sxe = new SimpleXMLElement($xml);
         foreach ($sxe->children() as $child){
            foreach($child as $key=>$item){
               echo $key.': '.$item.'<br />';
            }
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        • 2015-01-06
        • 1970-01-01
        • 2020-05-09
        • 1970-01-01
        • 1970-01-01
        • 2015-01-04
        相关资源
        最近更新 更多