PHP & insertBefore() = DOMException "Not Found Error"

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
^rooker
Site Admin
Posts: 1483
Joined: Fri Aug 29, 2003 8:39 pm

PHP & insertBefore() = DOMException "Not Found Error"

Post by ^rooker »

[PROBLEM]
I tried to use PHP's "DOMDocument::insertBefore()" to make sure that a certain XML node gets written at a given position, in order to satisfy an XSD.
PHP Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error' in /home/username/test/scripts/web_videos/fix_mets.php:191
Stack trace:
#0 /home/username/test/scripts/web_videos/fix_mets.php(191): DOMNode->insertBefore(Object(DOMElement), Object(DOMElement))
#1 /home/username/test/scripts/web_videos/fix_mets.php(223): fix_aspect_ratio(Array)
#2 {main}
thrown in /home/username/test/scripts/web_videos/fix_mets.php on line 191
As you can see, both arguments supplied to insertBefore() were DOMElement instances, and both were "introduced" to the DOMDocument:
The reference node was an existing element, and the new node to be "inserted before" was created using "createElement()":

Code: Select all

$dom = new DOMDocument;
[...]
$duration_node = $nodelist_duration->item(0);
$empty_node = $dom->createElement('aspect_ratio');
$dom->insertBefore($empty_node, $duration_node);
But it didn't work, throwing the above Exception.

[SOLUTION]
A nice Q&A on stackoverflow.com about Javascript "document.insertBefore throws error for unknown reason" then gave me the hint that I'd need to call the parent node's "insertBefore()" - not the main document's one.
So, I've changed the the last line of the above code to:

Code: Select all

$duration_node->parentNode->insertBefore($empty_node, $duration_node);
And it worked!
btw: I could have read the original documentation on the PHP website, where it says:
Exception "DOM_NOT_FOUND" is raised if refnode is not a child of this node.
Jumping out of an airplane is not a basic instinct. Neither is breathing underwater. But put the two together and you're traveling through space!
Post Reply