Jump to content

xml remove node


digitalgod

Recommended Posts

Hey guys,

 

I'm having problems deleting an xml node using php and I can't seem to find the problem...

 

this is what my xml file looks like

 

<?xml version="1.0" encoding="UTF-8"?>
<player showDisplay="yes" showPlaylist="no" autoStart="yes" topTitle="Player" skinColor="2">
<song path="mp3/beg.mp3" title="Omarion - Beg For It.mp3"/>
<song path="mp3/Show.mp3" title="Kat DeLuna - Run The Show"/>
<song path="mp3/wonder.mp3" title="Maroon 5 ft. Mims - Makes Me Wonder"/>
<song path="mp3/there.mp3" title="Sean Kingston - Take You There.mp3"/>
<song path="mp3/test.mp3" title="test.mp3"/>
</player>

 

and here's what I'm trying to do as a test to delete a node

$mp3file = new DomDocument();
$mp3file->load("mp3.xml");

$player = simplexml_load_file("mp3.xml");
$count = 0;

foreach($player->song as $song) {

if( $song['path'] == "mp3/test.mp3" )
{
$mp3file->documentElement->removeChild($mp3file->documentElement->childNodes->item($count));
$count--;
}

$count++;

}

$mp3file->save("mp3.xml");

 

but it doesn't delete anything... I tried removing the if statement just to see if it would delete all the nodes but it only deleted 2 of them.. any ideas what I'm doing wrong?

Link to comment
https://forums.phpfreaks.com/topic/95900-xml-remove-node/
Share on other sites

I'm definitely no expert but this works for me...

<?php
$xmlString = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<player showDisplay="yes" showPlaylist="no" autoStart="yes" topTitle="Player" skinColor="2">
<song path="mp3/beg.mp3" title="Omarion - Beg For It.mp3"></song>
<song path="mp3/Show.mp3" title="Kat DeLuna - Run The Show"></song>
<song path="mp3/wonder.mp3" title="Maroon 5 ft. Mims - Makes Me Wonder"></song>
<song path="mp3/there.mp3" title="Sean Kingston - Take You There.mp3"></song>
<song path="mp3/test.mp3" title="test.mp3"></song>
</player>
EOF;


$oXml = new DOMDocument;
$oXml->loadXML($xmlString);

$player = $oXml->documentElement;

$songs  = $player->getElementsByTagName('song');

foreach ($songs as $song) {
    
    $title = $song->getAttributeNode('title'); 
    
    $path  = $song->getAttributeNode('path');
    
    if ($path->value == "mp3/test.mp3") {
    
        $player->removeChild($song);
    }
    
}
echo $oXml->saveXML(); //view source to see result!
?>

 

Theres most likely a more efficient way but I hope that will get you started. Also, I don't think that short closing tags is allowed in XML.

Link to comment
https://forums.phpfreaks.com/topic/95900-xml-remove-node/#findComment-491822
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.