How to remove a node from a xml file?

Hello all,

This is my xml file:

<ruleset>
	<rule id="10">
	<name>Campaign 1</name>
		<match>
			<keyword>123</keyword>
			<keyword>car</keyword>
		</match>
		<results>
			<result>
				<title><![CDATA[Some cutom <b>title</b>]]></title>
				<body><![CDATA[This is result <b>body</b>! bla bla bla bla bla bla bla bla bla bla]]></body>
				<visibleurl><![CDATA[www.<b>ukr.net</b>]]></visibleurl>
				<clickurl>http://www.ukr.net/</clickurl>
			</result>
			<result>
				<title><![CDATA[Second <b>title</b>]]></title>
				<body><![CDATA[This is second body. Here could be your advertising!]]></body>
				<visibleurl><![CDATA[www.<b>ukr.net</b>]]></visibleurl>
				<clickurl>http://www.ukr.net/</clickurl>
			</result>
		</results>
	</rule>
	
	<rule id="77">
	<name>Campaign 2</name>
		<match>
			<keyword>abc</keyword>
			<keyword>qwe</keyword>
		</match>
		<results>
			<result>
				<title><![CDATA[Third title]]></title>
				<body><![CDATA[A title is a prefix or suffix added to someone's name to signify either veneration, an official position or a professional or academic qualification. <b>...</b>]]></body>
				<visibleurl><![CDATA[www.<b>ya.net</b>]]></visibleurl>
				<clickurl>http://www.ya.ru/</clickurl>
			</result>
		</results>
	</rule>
	
</ruleset>

I am trying to remove specific nodes, being set from the <rule id=“”> line
Using this code currently: wich isnt working

public function delete($id)
	{
		$filename = $_SERVER['DOCUMENT_ROOT']."/users/".$_SESSION[request::authHash()]['id']."/serp.xml";
		$handle = fopen($filename,'r+') or die("Cannot open file");
		$contents = fread($handle, filesize($filename));
		fclose($handle);
		$doc = new DOMDOcument; $doc->loadxml($contents); 
		$xpath = new DOMXpath($doc); 
		foreach($xpath->query('[rule id="'.$id.'"]') as $node) {   $node->parentNode->removeChild($node); } echo $doc->savexml();

		
		request::redirect('/admin/serp');
	}

How can i fix this?

Well not to be crude, but if you’re certain of the structure…


$in = file_get_contents($filename);
$start = strpos('<rule id="'.$id.'">', $in);
$end = strpos('</rule>',$in,$start);
$out = substr($in,0,$start).$substr($in,($end + 7));
$fp = fopen($filename,'w');
fwrite($fp,$out);
fclose($fp);

The main problem is that your XPath query is incorrect.

Yours looks like: [rule id="10"]
It should look something like: /ruleset/rule[@id="10"]

Here’s a good overview of the XPath syntax: schlitt.info/opensource/blog/0704_xpath.html

P.S. You should be getting a bunch of warning messages from PHP stating Warning: DOMXPath::query() [domxpath.query]: Invalid expression in [i]filename[/i] on line [i]number[/i]. Be sure to turn on displaying of errors, and set the error reporting level high enough to see warnings (ideally, to see all messages).