I am trying to remove an element from an XML file using SimpleXML, and i have a script that works but i woudl like to tweak it.

my current php file looks like this:

<?php

#CREATING THE HANDLER
#
$xml = simplexml_load_file('file.xml');

#
#LOOP THROUGH  THE <LINKGROUP> NODES
#
$linkGroup = $xml->linkGroup;

echo("<ul>");

#
#LOOP THROUGH  THE <LINKITEM> NODES (CHILD OF <LINKGROUP>
#
$loopcount = 0;
foreach($linkGroup->linkItem as $linkItem)
{
	$id = $linkItem['id'];

	if ( $id == $_GET["id"] )
	{
		break;
	}

	$loopcount += 1;
}

unset($linkGroup->linkItem[$loopcount]);

#
#WRITE THE RESULTS BACK TO THE XML FILE
#
file_put_contents('file.xml', $xml->asXml());
?>

<br>
The item has been deleted. <a href='index.php'>Return to list</a><br>

and my XML file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<linkCollection>
	<linkGroup id="Photoshop">
		<linkItem id="1">
			<title>Google</title>
			<description>This is the first link</description>
			<url>http://www.google.com</url>
		</linkItem>
		<linkItem id="2">
			<title>blairdee.info</title>
			<description>This is the second link</description>
			<url>http://www.blairdee.info</url>
		</linkItem>
		<linkItem id="3">
			<title>Microsoft Windows 7 Website</title>
			<description>This is the third link</description>
			<url>http://www.microsoft.com/windows7</url>
		</linkItem>
		<linkItem id="4">
			<title>Fandango</title>
			<description>This is the fourth Link</description>
			<url>http://www.fandango.com</url>
		</linkItem>
	</linkGroup>
</linkCollection>

so in my php file, i am taking the id passed in the querystring and looping through my xml file till i find the <linkItem> with that id. when i find the <linkItem> with that id, i break out of the loop and then remove the element.

but i am wondering how i woudl go about removing the element from right inside the loop.

i tried putting the following inside the if statement, inside the loop:
unset($linkItem);

but although it doesn't throw an error, the element does not get removed.

    Write a Reply...