简体   繁体   中英

PHP Accessing SimpleXMLElement Object array keys

In the following SimpleXMLElement Object $results , I would like to remove the element with ID 13011146 from the TEST array. I'm not sure how to properly access the array key with value 1 , so I'm using a counter $i , but that gives me an error Node no longer exists , pointing to the foreach line.

TL;DR : How do you unset $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++;
}

a more elegant way; it gives you the same results without using $attributes[ '@attributes' ] :

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

For specific key/value pair, we can use like:

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

Hope it helps !

Try this:

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

try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM