【问题标题】:PHP can't load XML file from http://comment.bilibili.tvPHP 无法从 http://comment.bilibili.tv 加载 XML 文件
【发布时间】:2016-04-22 06:39:53
【问题描述】:

我使用下面的简单代码从 Internet 加载 XML 文件并读取它:

$doc = simplexml_load_file($url);

或此代码:

$doc = new DOMDocument();
$doc->load($url);

或 tis 代码:

$doc = file_get_contents($url);

它们运行良好,除了一个网站:http://comment.bilibili.tv/

如果 $url 类似于“http://comment.bilibili.tv/681965.xml”, file_get_contents() 会得到乱码,simplexml_load_file() 会得到空对象。

但如果我将它下载到本地硬盘,并将 $url 更改为“681965.xml”, 代码有效。

那么问题是什么?我该如何解决?

【问题讨论】:

  • 您需要更具体地了解您看到的错误。 “弄乱代码”是什么意思?您是否看到错误消息?您是否尝试过类似$doc = file_get_contents($url); file_put_contents('test.txt', $doc); 并在文本编辑器中打开它?如果是这样,你能描述一下你的发现,或者给我们看一个小例子吗?

标签: php xml dom simplexml file-get-contents


【解决方案1】:

comment.bilibili.tv 的响应是使用 DEFLATE 算法压缩的,正如您在 Web 浏览器中请求时从 Content-Encoding 标头中看到的那样。

我不确定为什么 PHP 在您请求它并为您处理它时没有注意到它,但您可以在调用 file_get_contents 后通过 gzinflate 传递内容来绕过它。然后您可以根据需要将内容加载到DOMDocumentsimplexml_load_string

$content = gzinflate(file_get_contents("http://comment.bilibili.tv/681965.xml"));

您还可以使用compression filters 构建一个可以直接传递给simplexml_load_fileDOMDocument::load 的URL。

$url = "php://filter/zlib.inflate/resource=http://comment.bilibili.tv/681965.xml";

$doc = simplexml_load_file($url);

$doc = new DOMDocument();
$doc->load($url);

$doc = file_get_contents($url);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多