-1

i tried to find it out with previous answers but i cannot do it propperly, i followed Stefan's answer Remove a child with a specific attribute, in SimpleXML for PHP

and my code is

xml:

    <?xml version="1.0" encoding="utf-8"?>
    <res>
    <items>
    <item>
    <id>1</id>
    <a>asdasda</a>
    </item>
    <item>
    <id>1</id>
    <a>bababba</a>
    </item>
    <id>2</id>
    <a>sasdasda</a>
    </item>
    <item>       
    <id>3</id>
    <a>sasdasda</a>
    </item>
    <item>
    <id>4</id>
    <a>sasdasda</a>
    </item>
    <item>
    <id>5</id>
    <a>sasdasda</a>
    </item>
    <item>
    <id>6</id>
    <a>sasdasda</a>
    </item>
    </items>
    </res>

and php is

   <?php
   $id="1";
   $xml = simplexml_load_file("filtracjaxml.xml") ;

   foreach($xml->items->item->id as $id)
   {
       if($id == '1') {
           $xml=dom_import_simplexml($id);
           $xml->parentNode->removeChild($xml);
       }
   }
   echo $xml->asXml();
   ?>

when i try to run it i have

    Fatal error: Call to undefined method DOMElement::asXml() in filtruj.php on line 14

EDIT:

What I want is deleting the whole 'item' not only 'id' - all items with id = 1

so i changed the code :

    foreach ( $xml->items->item as $id )
    {
        if ( $id->id == '1' ) {
            $tmp = dom_import_simplexml($id);
            $tmp->parentNode->removeChild($tmp);
        }
    }
    echo $xml->asXml();

and it deletes only the first item. Could you tell me why? what is wrong in the code written above?

Community
  • 1
  • 1
andrewpo
  • 361
  • 1
  • 6
  • 14

1 Answers1

1
<?php
$id="1";
$xml = simplexml_load_file("filtracjaxml.xml") ;

foreach ( $xml->items->item->id as $id )
{
    if ( $id == '1' ) {
        $tmp = dom_import_simplexml($id);
        $tmp->parentNode->removeChild($tmp);
    }
}
echo $xml->asXml();
?>
augustknight
  • 448
  • 2
  • 7
  • it worked but not as i wanted - i made a mistake. What I want is to delete all items with a child id = 1. – andrewpo Mar 23 '12 at 20:56