我使用PHP的simplexml_load_file()函数调用一个API,该API根据发送的时间戳返回更改的结果.
因此,API仅返回自我的时间戳以来已更改的结果.我遇到的问题是,如果时间戳记过早并且没有可返回的API结果,那么它不会返回正确的XML文件,而是会返回一个空白页.
这导致了simplexml_load_file的各种问题
这是我可以运行的简单测试…
$xml = 'http://api.rescuegroups.org/rest/?key=CZivWWGD&type=orgs&limit=300&updatedAfter=1361941202&startPage=1';
$xmlObj = new SimpleXMLElement($xml, NULL, TRUE);
这导致…
Warning: SimpleXMLElement::__construct(): http://api.rescuegroups.org/rest/?key=CZivWWGD&type=orgs&limit=300&updatedAfter=1361941202&startPage=1:1: parser error : Document is empty in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php on line 9
Warning: SimpleXMLElement::__construct(): in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php on line 9
Warning: SimpleXMLElement::__construct(): ^ in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php on line 9
Warning: SimpleXMLElement::__construct(): http://api.rescuegroups.org/rest/?key=CZivWWGD&type=orgs&limit=300&updatedAfter=1361941202&startPage=1:1: parser error : Start tag expected, '<' not found in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php on line 9
Warning: SimpleXMLElement::__construct(): in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php on line 9
Warning: SimpleXMLElement::__construct(): ^ in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php on line 9
Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php:9 Stack trace: #0 E:\Server\htdocs\labs\freelance\dogAPI\testorg.php(9): SimpleXMLElement->__construct('http://api.resc...', 0, true) #1 {main} thrown in E:\Server\htdocs\labs\freelance\dogAPI\testorg.php on line 9
现在,如果我向API传递了一个时间戳,该时间戳又返回到有结果的地方,那么它将返回一个完美的XML文档.
我正在寻找一种方法来防止这种讨厌的错误发生?
解决方法:
$xml = @simplexml_load_file('http://api.rescuegroups.org/rest/?key=CZivWWGD&type=orgs&limit=300&updatedAfter=1361941202&startPage=1');
if(false !== $xml)
{
// Do anything with xml
}
如果有错误@隐藏它并返回false