Page 1 of 1

File manipulation

Posted: Sat May 05, 2007 7:56 am
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).

Posted: Sat May 05, 2007 8:28 am
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.

Reply

Posted: Sat May 05, 2007 8:35 am
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.