I am experiencing a very odd error. I am writing a function to validate XML based on element names, in this case passed in as an array. First, I normalize the input to a SimpleXMLElement object; in this case I am passing in a DOMDocument, and I tested it, it is converting correctly to SimpleXMLElement.
What confuses me is that calling getName() will throw the following:
PHP Fatal error: Call to a member function getName() on a non-object
But using exit($xml->getName()) (or echo) will return the correct result – the root element name!
Relevant code:
function validateXML($xml, $format='') {
(get_class($xml) !== 'SimpleXMLElement') ?
((get_class($xml) === 'DOMDocument') ?
$xml = simplexml_import_dom($xml)
: $xml = simplexml_load_string($xml))
: $xml = $xml;
$rootName = ($xml->getName());
if ($rootName != $format[0]) {
exit($xml->getName())));
}
Also, in case it matters, the server is running PHP 5.3
I am very new to PHP so help is extremely appreciated!
P.S. To be clear about what exactly is going on, the following code:
function validateXML($xml, $format='') {
echo(get_class($xml);
$xml = simplexml_import_dom($xml);
echo(get_class($xml);
echo($xml->getName());
}
outputs to the server
DOMDocument
SimpleXMLElement
'ElementName' (the correct root name of my XML document)
… so it appears to be working, except that the fatal error still gets thrown.
Your code (assuming it is close enough to what you have written in the question) will fail when
$xmlis invalid XML, becausesimplexml_load_string():If you still do not see this, I suggest rewriting your code using
ifstatements instead of tertiary statements. Your function, when$xmlis notSimpleXMLElementinstance, norDOMDocumentinstance, will be effectively coming down to the following function: