0

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?

krummens
  • 837
  • 2
  • 17
  • 38
  • 1
    I'd recommend using SimpleXML: http://php.net/manual/en/book.simplexml.php – Bitwise Creative Feb 06 '15 at 17:55
  • I don't know where to start. I have code to insert a `` into the file. but i need to be able to delete one – krummens Feb 06 '15 at 19:26
  • http://stackoverflow.com/questions/16148212/delete-node-with-simplexml – michi Feb 06 '15 at 23:20
  • that question wants all of the nodes deleted. I only want one of them. @michi – krummens Feb 06 '15 at 23:51
  • @phprunner, I'd like to motivate you to start pulling together the information that is there on SO and apply it to your case. edit your question, share what you have tried and evolve your questions from there. – michi Feb 07 '15 at 00:21
  • @michi: i have been for the entire day to figure out how to do this. I have tried many things and had no results. I am sorry but I can't provide any code. Is there anything else I can provide? more info about what I am trying to do? – krummens Feb 07 '15 at 00:52
  • 1
    Provide the code that failed. Additionally it doesnt matter that the answer deletes all the nodes... It show you how to delete a node... so then you just need to get the specific node you need to delete. – prodigitalson Feb 07 '15 at 01:23

2 Answers2

2

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

Community
  • 1
  • 1
krummens
  • 837
  • 2
  • 17
  • 38
  • good job, mark the answer as accepted if it fits your needs. If not, edit the question to ask differently – michi Feb 07 '15 at 13:31
0

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);
ThW
  • 19,120
  • 3
  • 22
  • 44