Remove a xml node with specific attribute ?

Discussion in 'PHP' started by 123GoToAndPlay, Oct 6, 2009.

  1. #1
    Hi all,

    I am using simplexml and xpath to look for a particular node.
    I can find the correct node but i can't remove it

    testing function so far
    
    function deleteXMLnode($lang, $xmlNode) {
    	//get the xml file
    	$xml = simplexml_load_file("../assets/xml/content-".$lang."2.xml", 'SimpleXMLElement' , LIBXML_NOCDATA);
    	//find the right node to delete based on attribute
    	$data  = $xml->xpath("//page[@gotoURL='".$xmlNode."']");
    	//test find query
    	foreach($xml->xpath("//page[@gotoURL='".$xmlNode."']") as $found) {
    			echo "test: ".$found->pageTitle;//this is the right node
    			unset($xml->$found);
    		}
    	//exit;
    
    	//actual delete
    	//unset($xml->$data);
    	echo $xml->asXML();
    	exit;
    	//save the new xml
    	file_put_contents("../assets/xml/content-".$lang."2.xml", $content);
    }
    deleteXMLnode('en', 'produkt/name')
    
    Code (markup):
    any ideas?
     
    123GoToAndPlay, Oct 6, 2009 IP
  2. 123GoToAndPlay

    123GoToAndPlay Peon

    Messages:
    669
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    ok i think i found a workable solution (tx to http://www.tutorialhero.com/click-61225-deleting_elements_nodes_using_simple_xml.php)

    
    function deleteXMLnode2($lang, $xmlNode) {
    	 //header ("content-type: text/xml");
    	//Get the XML file 
    	$data = file_get_contents("../assets/xml/content-".$lang.".xml");
    	//Make the XML file into a Simple XML Object
    	$xml = new SimpleXMLElement($data);
    	//Loop through the nodes and
    	//If we find the node with the attribute 
    	foreach($xml->xpath("//page[@gotoURL='".$xmlNode."']") as $found){ 
    			//We make that node into a DOM object
    			$dom = dom_import_simplexml($found);
    			//Then we delete that node 
    			$dom->parentNode->removeChild($dom); 
    	}
    	$content = $xml->asXml();
    	//exit;
    	//save the new xml
    	file_put_contents("xml/content-".$lang.".xml", $content);
    }
    
    Code (markup):
    I just have to figure out the different parent and childs used in my particular xml file.
     
    123GoToAndPlay, Oct 6, 2009 IP