Last active
January 15, 2016 09:09
-
-
Save ZiTAL/18275313f7708d287096 to your computer and use it in GitHub Desktop.
php: dom order nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> | |
<root> | |
<zone type=\"zone_right\"> | |
a | |
</zone> | |
<zone type=\"zone_right\"> | |
b | |
</zone> | |
<zone type=\"zone_left\"> | |
c | |
</zone> | |
</root>"; | |
$dom = orderDom($xml); | |
echo $dom->saveXML(); | |
// zone_right, zone_left-aren antzean jarri | |
function orderDom($xml) | |
{ | |
$dom = new DOMDocument('1.0', 'utf-8'); | |
$dom->loadXML($xml); | |
$root = $dom->getElementsByTagName('root')->item(0); | |
$zones = $root->getElementsByTagName('zone'); | |
for($i=0;$i<$zones->length;$i++) | |
{ | |
$type = $zones->item($i)->getAttribute('type'); | |
if($type==='zone_right') | |
{ | |
$j = $i+1; | |
if($j<$zones->length) | |
{ | |
$next_type = $zones->item($j)->getAttribute('type'); | |
if($next_type==='zone_left') | |
{ | |
$parent = $zones->item($j)->parentNode; | |
// zone left clonatu | |
$tmp = $zones->item($j)->cloneNode(true); | |
// zone right-en aurrean jarri | |
$parent->insertBefore($tmp, $zones->item($i)); | |
// indizea + 1, insertBefore egiterakoan indizeak aldatu egiten dira, nodo 1 gehiago sartu dugulako | |
// zone left originala ezabatu | |
$parent->removeChild($zones->item($j+1)); | |
return orderDom($dom->saveXML()); | |
} | |
} | |
} | |
} | |
return $dom; | |
} | |
/* output: | |
<?xml version="1.0" encoding="UTF-8"?> | |
<root> | |
<zone type="zone_left"> | |
c | |
</zone><zone type="zone_right"> | |
a | |
</zone> | |
<zone type="zone_right"> | |
b | |
</zone> | |
</root> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment