file_get_contents(): stream does not support seeking / PHP 这个行为什么时候改变了?

file_get_contents(): stream does not support seeking / When was PHP behavior about this changed?

关于此的 PHP 行为什么时候改变的?

它来自哪个 PHP 版本?


Warning: file_get_contents(): stream does not support seeking in /simple_html_dom.php

Warning: file_get_contents(): Failed to seek to position -1 in the stream in /simple_html_dom.php


include('parser/simple_html_dom.php');
$url = "https://en.wikipedia.org/wiki/Stack_Overflow";
$html = file_get_html($url);
if ($html !== false) {
  foreach($html->find('div#mw-content-text') as $item){
    $item->plaintext;
  }
}

file_get_contents(): stream does not support seeking PHP

您正在使用远程文件。搜索仅支持本地文件。

在使用 file_get_html 之前,您可能需要将文件复制到本地文件系统。它应该在本地主机上工作正常。

当我将它从一个系统移动到另一个系统时,我的页面上遇到了同样的问题,我能够通过删除偏移量引用来更改 simple_html_dom.php 文件(没有给我带来任何进一步的问题).

simple_html_dom.php 的第 75 行:

$contents = file_get_contents($url, $use_include_path, $context, $offset);

我删除了对 $offset 的引用:

$contents = file_get_contents($url, $use_include_path, $context);

不,我的页面工作正常。不承担任何其他损坏的责任! :)

改变

function file_get_html(..., $offset = -1,...)

function file_get_html(..., $offset = 0,...)

在simple_html_dom.php

设置 $offset = 0

有效!

其他人分享了解决方案,但没有人分享原因。我不知道为什么 PHP 7.0 和 7.1 之间有区别,但是 PHP.net docs for this function 说:

Seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.

我可以确认删除第 75 行 file_get_contents 中的偏移参数对我有效 and/or 在第 70 行的 file_get_html 函数中将偏移设置为 0 也有效。

我猜想偏移参数永远不会用于非本地文件,因为:

The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.

希望这有助于消除任何困惑。对于外部资源,从头开始流式传输是有意义的。

您不需要编辑供应商文件。只需将您的请求更改为:

$html = HtmlDomParser::file_get_html( "https://www.google.com/");

至:

$html = HtmlDomParser::file_get_html( "https://www.google.com/", false, null, 0 );

问题是 Simple HTML DOM 使用的默认偏移量是“-1”,而您希望它是“0”。幸运的是它接受它作为参数,这意味着您可以轻松更改它而无需更改 Simple HTML DOM source.

注意:此兼容性问题已在 v1.7+

中修复

首先,尝试改变simple_html_dom.php喜欢

  • 从第 75 行的 file_get_contents(...) 中删除偏移参数

  • 或在第 70 行的 file_get_html 函数中将偏移量设置为 0

如果还是不行 ???像我一样

那么这意味着你有最新版本的PHP,你需要从https://sourceforge.net/projects/simplehtmldom/

下载最新版本的simple_html_dom.php

之后,它适用于我的每台机器和系统