简体   繁体   中英

getName() call on SimpleXMLElement returns fatal error “call to member function on a non-object”

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!

PS 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 $xml is invalid XML, because simplexml_load_string() :

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or FALSE on failure .

If you still do not see this, I suggest rewriting your code using if statements instead of tertiary statements. Your function, when $xml is not SimpleXMLElement instance, nor DOMDocument instance, will be effectively coming down to the following function:

function validateXML($xml, $format='') {
    simplexml_load_string($xml);
    $rootName = ($xml->getName());
    if ($rootName != $format[0]) {
        exit($xml->getName());
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM