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
user___
Forum Contributor
Posts: 297 Joined: Tue Dec 05, 2006 3:05 pm
Post
by user___ » Tue May 08, 2007 3:45 am
Hi guys,
I need to know how to append a child element to another child. This is the .xml file:
Code: Select all
...
<states>
<cities>
<quarters>
<street id="1" />
</quarters>
</cities
<states>
...
I need to append streets.
volka
DevNet Evangelist
Posts: 8391 Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger
Post
by volka » Tue May 08, 2007 6:56 am
Is there something to identify the "place" where you want to add a new element?
user___
Forum Contributor
Posts: 297 Joined: Tue Dec 05, 2006 3:05 pm
Post
by user___ » Tue May 08, 2007 7:25 am
No, there is just a tag and in quarters besides ids there are some more attributes.
BTW:The XML can be edited as it needs to be so if there should be something anywhere I can put it there.
Do you have any ideas of how to achieve this in Php?
volka
DevNet Evangelist
Posts: 8391 Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger
Post
by volka » Tue May 08, 2007 7:41 am
user___ wrote: No, there is just a tag and in quarters besides ids there are some more attributes.
no but yes? attributes are good for identifying the location, e.g.
id , even the name says it.
With php5's dom extension you can do:
Code: Select all
$xml = <<< eox
<xml>
<states>
<cities>
<quarters id="6348">
<street id="1" />
</quarters>
</cities>
</states>
</xml>
eox;
$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$nodeset = $xpath->query('//quarters[@id=6348]');
if ( 1!=$nodeset->length ) {
echo 'error: ', $nodeset->length, ' quarters found';
}
else {
$newElement = $dom->createElement('street');
$newElement->setAttribute('id', '45');
$nodeset->item(0)->appendChild($newElement);
}
echo $dom->saveXML();
user___
Forum Contributor
Posts: 297 Joined: Tue Dec 05, 2006 3:05 pm
Post
by user___ » Tue May 08, 2007 8:07 am
Thank you, volka but I need a little modification in this script and it will suit my needs at all. Well, is it possible to get the last id(I mean not 6348 but if there are 9393 ids to get 9393 as a result).
Is this possible or is there a workaround to get the last id and then append it on it.