krummens
krummens

Reputation: 867

delete a node of an xml file with php

I am trying to delete part of an xml file with php. the links.xml file looks like this:

<?xml version='1.0' encoding='UTF-8'?>
<pages>
<link url="http://example.com">
<title>Who won the world series</title>
</link>
<link url="http://anotherexample.com">
<title>Who won the super bowl</title>
</link>
</pages>

As you can see, I have two different entries in the file above. in my actual file I have many of these. What I want to do is, using php, delete one of the <link> node from the file. How could I go about doing it?

Upvotes: 0

Views: 1038

Answers (2)

ThW
ThW

Reputation: 19502

It is easy with DOM + XPath:

$dom = new DOMDocument();
$dom->load($sourceFile);
$xpath = new DOMXPath($dom);

foreach ($xpath->evaluate('//link[@url="http://example.com"]') as $node) {
  $node->parentNode->removeChild($node);
}

echo $dom->save($targetFile);

Upvotes: 0

krummens
krummens

Reputation: 867

I figured it out how to do it by looking at this question. You can go about it by doing this:

<?php
$fild = '../XML/link.xml';
$sxe = simplexml_load_file($file);

$nodeURL = $sxe->xpath('link[@url="http://example.com"]');
$noteToRemove = $nodeURL[0];
unset($noteToRemove[0]);

$sxe->asXML($file);
?>

This would work for the xml file I added above

Upvotes: 2

Related Questions