Jump to content

DOMDocument


FredAt

Recommended Posts

Hello All,

 

I need to take an XML document, modify some of the nodes in it and then perform a selective reordering of a subset of nodes. The modification I have done without too much difficulty - extracting the current node as nodeValue, operating on the nodeValue to generate a new node with the desired structure and then replaceChild to replace the old node.

 

However, when I looked at reordering I hit a stumbling block. Much to my surprise I found that there appear to be no methods of DOMNode/DOMElement/DOMDocument to help me do the reordering.  I thought I would first take out the nodes that require reordering and then add them back in.  And then I found that on my local installation (PHP 5.2) last_child and lastChild both produced error messages.

 

Am I barking up the wrong tree here? Do I need to look at something other than DOMDocument?  I'd hugely appreciate any help.

Link to comment
https://forums.phpfreaks.com/topic/185470-domdocument/
Share on other sites

There's likely not One-True-Answer™ to your problem.  "Sorting" with the DOM is simply a matter of (removing and) inserting the node in the correct place in the document.

 

Here's one example, which might not be applicable in your case (your XML and intended output etc. would be nice) just to whet your whistle.

 

$doc = new DOMDocument("1.0", "UTF-8");
$doc->formatOutput = TRUE;
$doc->preserveWhiteSpace = FALSE;
$doc->loadXML('
<root>
<parent>
	<child name="bob"/>
	<child name="may"/>
	<child name="amy"/>
	<child name="joe"/>
</parent>
</root>
');

// Gather "child" nodes into an array
$children = array();
foreach ($doc->getElementsByTagName("child") as $child) {
$children[] = $child;
}

// Sort those nodes by their name attribute
function sort_by_name($a, $b) {
return strnatcasecmp($a->getAttribute("name"), $b->getAttribute("name"));
}
usort($children, 'sort_by_name');

// Go through the nodes in sorted order, removing and re-adding them in sequence
foreach ($children as $child) {
$parent = $child->parentNode;
$parent->removeChild($child);
$parent->appendChild($child);
}

// Hello, XML!
echo $doc->saveXML();

 

Output (The child nodes sorted in alphabetical order.)

<?xml version="1.0"?>
<root>
  <parent>
    <child name="amy"/>
    <child name="bob"/>
    <child name="joe"/>
    <child name="may"/>
  </parent>
</root>

 

The main point is to pluck them out of the document then put them back in in your desired place.

Link to comment
https://forums.phpfreaks.com/topic/185470-domdocument/#findComment-979402
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.