By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,949 Members | 1,827 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,949 IT Pros & Developers. It's quick & easy.

Delete element in xml file by using php

P: n/a
Hi,
I have a application which has a xml file reading and wrting. I want
to remove some element in xml file by using php.
<?xml version="1.0" encoding="UTF-8"?>
<element1>
<subelement1>aa</subelement1>
<subelement2>aa</subelement2>
</element1>
How to remove "<subelement1>aa</subelement1>" that elements and save
back to same or other xml file.
Aug 23 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Samudaya wrote:
Hi,
I have a application which has a xml file reading and wrting. I want
to remove some element in xml file by using php.
<?xml version="1.0" encoding="UTF-8"?>
<element1>
<subelement1>aa</subelement1>
<subelement2>aa</subelement2>
</element1>
How to remove "<subelement1>aa</subelement1>" that elements and save
back to same or other xml file.
Check out the PHP manual:

SimpleXML: <URL:http://www.php.net/manual/en/book.simplexml.php>
DOM (PHP 5): <URL:http://www.php.net/manual/en/intro.dom.php>

If you're stuck with PHP 4:
<URL:http://www.php.net/manual/en/ref.domxml.php>

--
Curtis (http://dyersweb.com/)
Aug 23 '08 #2

P: n/a
<?xml version="1.0" encoding="UTF-8"?>
<element1>
* * <subelement1>aa</subelement1>
* * <subelement2>aa</subelement2>
</element1>

How to remove *"<subelement1>aa</subelement1>" that elements and save
back to same or other xml file.
first of all, i wouldnt call each element element1 and element2 etc
just element. You can store the meta data such as a number as an
attribute instead. I'd do something like this (off the top of my head
and untested)...
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<element num="1">
<subelement1>aa</subelement1>
<subelement2>aa</subelement2>
</element>
</xml>
XML;

$dom = new DOMDocument();
$dom->loadXML($xml);

$xpath = new DomXpath($dom);

$result = $xpath->query("//element");
$result->parentNode->removeChild($result->item(0));

$dom->saveXML();

Aug 23 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.