PHP XML验证在有效的XML上失败

I use the following function to validate XML coming from a Web API before trying to parse it:

function isValidXML($xml) {
    $doc = @simplexml_load_string($xml);
    if ($doc) {
        return true;
    } else {
        return false;
    }
}

For some reason, it fails on the following XML. While it's a bit light in content, it looks valid to me.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><connection-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" />

Why would this fail? I tried another method of validate the XML that used DOMDocument and libxml_get_errors(), but it was actually more fickle.

EDIT: I should mention that I'm using PHP 5.3.8.

I think your interpretation is just wrong here – var_dump($doc) should give you

object(SimpleXMLElement)#1 (0) {
}

– but since it is an “empty” SimpleXMLElement, if($doc) considers it to be false-y due to PHP’s loose type comparison rules.

You should be using

if ($doc !== false)

here – a type-safe comparison.

(Had simplexml_load_string actually failed, it would have returned false – but it didn’t, see var_dump output I have shown above, that was tested with exactly the XML string you’ve given.)

SimpleXML wants some kind of "root" element. A self-closing tag at the root won't cut it.

See the following code when a root element is added:

<?php

function isValidXML($xml)
{
    $doc = @simplexml_load_string($xml);
    if ($doc) {
        return true;
    } else {
        return false;
    }
}

var_dump(isValidXML('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root><connection-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" /></root>'));

// returns true

print_r(isValidXML('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root><connection-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" /></root>'));

// returns 1

?>

Hope that helps.