1

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++;
}
1
  • can you provide the XML for main SimpleXMLElement Object Commented Jan 5, 2012 at 10:28

4 Answers 4

0

try this

$node = $results->children();
unset($node[1]);
Sign up to request clarification or add additional context in comments.

Comments

0
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]);    
        }
    }
}

2 Comments

Sorry, misread your structure: Should be fixed by the call to children() - see edited version
Now we don't even enter in the first foreach loop :s If I remove children() then a match if found for $a and $b but again the value of $key is wrong.
0

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 !

Comments

0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.