为什么我的simplexml_load_file不起作用?
我一直在用simplexml_load_file获取XML内容,任何想法为什么它不起作用? ?是否有事情做与下面的源..为什么我的simplexml_load_file不起作用?
$Url='http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS';
$XML=simplexml_load_file($Url);
对于FOM原因,如果你打开这个链接在浏览器,它的XML。如果你试图让我通过PHP这是JSON。 试试这个代码
$Url='http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS';
$fileContent = json_decode(file_get_contents($Url));
是的,我发现一样,反正谢谢...;) – 2014-12-07 17:12:54
你应该使用:
$Url='http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS';
$XML=simplexml_load_file(file_get_contents($Url));
这并没有解决问题,仍然没有工作......我也试过file_get_contents然后simplexml_load_string,用尽想法...:/ – 2014-12-06 16:31:00
而且你也不应该使用它。在一定程度上,file_get_contents以及simplexml_load_file使用完全相同的例程。接下来,答案中给出的代码显然是错误的,它可能意味着使用simplexml_load_string而不是simplexml_load_file。 -1。 – hakre 2014-12-22 11:34:52
发现原来的file_get_contents返回JSON这样:
$ X = json_decode(的file_get_contents( $ URL));
的伎俩......
有你的代码,以防止你找出什么很快会在这里对你自己(以及如何找到一个解决方案)两个小的(但常见的)错误。
首先,你没有做任何错误检查。如果无法打开文件,simplexml_load_file()
将返回FALSE
。
$xml = simplexml_load_file($url);
if (!$xml) {
// error opening the URL
return false;
}
这还不是非常丰富的,你可以现在只是让PHP错误报告/日志真正看到其产生的误差:
警告:使用simplexml_load_file():HTTP // :数据中心。 biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS:1:分析器错误:开始标记预期, '<' 中找不到[...]
警告:使用simplexml_load_file():{ “ASOF” : “2014-12-22T11:45:50.5976703 + 00:00”, “RaceCount”:25, “行”:[{ “等级”:” 1" ,” [...]
警告:使用simplexml_load_file()^在[...]
这已经预示着HTTP请求到该URL不提供XML,但是JSON(看到第二个警告)。
这是很容易通过告诉服务器接受此XML验证:
stream_context_set_default(['http' => ['header' => "Accept: text/xml"]]);
$xml = simplexml_load_file($url);
whcih现在只是工作,现在服务器提供XML可以通过正确解析和的SimpleXMLElement创建。
的完整代码例如:
<?php
$url = 'http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS';
stream_context_set_default(['http' => ['header' => "Accept: text/xml"]]);
$xml = simplexml_load_file($url);
if (!$xml) {
// error opening the file
var_dump(libxml_get_errors());
return false;
}
$xml->asXML('php://output');
输出:
<?xml version="1.0"?>
<CupResultsResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/sportapi"><AsOf>2014-12-22T11:45:50.5976703+00:00</AsOf><RaceCount>25</RaceCount><Rows><CupResultRow>[...]
此代码示例的the answer of a very similar question一个较短的版本,其覆盖相同的接地:
对于运行ASP.NET的Microsoft-IIS服务器,这种行为似乎很典型,最有可能是一些REST API组件。
这不是一个文件。这是一个URL。 – 2014-12-06 16:17:21
你说得对,我认为这将是与URL的东西,但这个网址是生成XML输出,不是吗?你能给我建议如何得到结果吗? – 2014-12-06 16:34:17
@MichalSlesingr:请启用PHP错误报告和日志记录。然后看看实际的错误消息。另请参见:[如何在PHP中获取有用的错误消息?](http://*.com/q/845021/367456) – hakre 2014-12-22 11:40:55