File manipulation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
user___
Forum Contributor
Posts: 297
Joined: Tue Dec 05, 2006 3:05 pm

File manipulation

Post by user___ »

Hi guys,
I have some files which need to be manipulated from Php. They have to do with registers and they are in XML.
My main file is something like:

Code: Select all

...XML
<staff>
   <personFile id="1" name="Person's name" />
   <personFile id="2" name="Person's name" />
   <personFile id="3" name="Person's name" />
</staff>
<employees>
   <personFile id="4" name="Person's name" />
   <personFile id="5" name="Person's name" />
   <personFile id="6" name="Person's name" />
</employees>
<others>
   <personFile id="7" name="Person's name" />
   <personFile id="8" name="Person's name" />
   <personFile id="9" name="Person's name" />
</others>
...XML
Then I have a .xml file for each of them.

What I am asking here is how to delete from this.xml file without any messing and the other questionof mine is how to rename ids(What I mean is when I delete for example the fourth person others after it to become with one less).
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

e.g. with php5's dom extension

Code: Select all

<?php
$xml = <<< eox
<root>
<staff>
	<personFile id="1" name="Person's name" />
	<personFile id="2" name="Person's name" />
	<personFile id="3" name="Person's name" />   
</staff>
<employees>
   <personFile id="4" name="Person's name" />
   <personFile id="5" name="Person's name" />
   <personFile id="6" name="Person's name" />
</employees>
<others>
   <personFile id="7" name="Person's name" />
   <personFile id="8" name="Person's name" />
   <personFile id="9" name="Person's name" />
</others>
</root>
eox;


$id = 6;

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

$dom->loadxml($xml);
$xpath = new DOMXPath($dom);
$nodeset = $xpath->query('//personFile[@id='.$id.']');
foreach($nodeset as $node) {
	$node->parentNode->removeChild($node);
}

echo $dom->savexml();
Don't reassign ids.
user___
Forum Contributor
Posts: 297
Joined: Tue Dec 05, 2006 3:05 pm

Reply

Post by user___ »

Thank you, man. You are great. I will test this on my local machine but my host is still suing Php 4.x. Any solution for it.
Post Reply