PHP & insertBefore() = DOMException "Not Found Error"
Posted: Tue Jul 17, 2012 2:08 pm
[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.
The reference node was an existing element, and the new node to be "inserted before" was created using "createElement()":
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:
And it worked!
btw: I could have read the original documentation on the PHP website, where it says:
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.
As you can see, both arguments supplied to insertBefore() were DOMElement instances, and both were "introduced" to the DOMDocument: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
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);
[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);
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.