PHP fsockopen()/fread() 返回困惑的数据

标签 php fread fsockopen

我使用 fsockopen() 和 fread() 读取了一些 URL,并得到了此类数据:

      <li
10 
></li>
      <li
9f 
>asd</li>

d  
          <li
92 

这完全是一团糟O_O

--

使用 file _ get _contents() 函数时,我得到这种数据:

<li></li>
      <li>asd</li>

哪个是正确的!那么,到底出了什么问题呢?我在 Windows 服务器和 Linux 服务器上尝试过,两者的行为相同。而且他们甚至没有相同的 PHP 版本。

--

我的 PHP 代码是:

$fp = @fsockopen($hostname, 80, $errno, $errstr, 30);
if(!$fp){
    return false;
}else{
    $out = "GET /$path HTTP/1.1\r\n";
    $out .= "Host: $hostname\r\n";
    $out .= "Accept-language: en\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);

    $data = "";
    while(!feof($fp)){
        $data .= fread($fp, 1024);
    }
    fclose($fp);

感谢任何帮助/提示,​​现在一整天都在想:/

哦,我不能使用 fopen() 或 file _ get _contents() 因为我的脚本运行的服务器没有启用 fopen 包装器 > __ <

我真的很想知道如何解决这个问题,只是出于好奇。而且我认为我无论如何都不能在该服务器上使用任何额外的库。

最佳答案

关于您的“奇怪数据”问题,这可能是因为您请求数据的服务器正在以分块模式传输数据。

在浏览器中调用相同的 URL 时,您可以查看 HTTP header ;这些标题之一可能是这样的:

Transfer-encoding: chunked


引用wikipedia's article on that matter :

Each non-empty chunk starts with the number of octets of the data it embeds (size written in hexadecimal) followed by a CRLF (carriage return and line feed), and the data itself. The chunk is then closed with a CRLF. In some implementations, white space characters (0x20) are padded between chunk-size and the CRLF.

The last chunk is a single line, simply made of the chunk-size (0), some optional padding white spaces and the terminating CRLF. It is not followed by any data, but optional trailers can be sent using the same syntax as the message headers.

The message is finally closed by a final CRLF combination.

这看起来与您得到的很接近...所以我猜这就是问题所在。


据我记得,curl 知道如何处理这个问题 - 所以,简单的方法是使用 curl而不是fsockopen之类的

使用curl通常比使用套接字更好:它可以解决您可能遇到的许多问题;就像这个;-)


另一个想法是,如果您的服务器上没有启用curl,则可以使用一些基于 fsockopen 的现有库——希望它能够为您处理这些事情。

例如,我曾与 Snoopy 合作过一些时间 ;也许它已经知道如何处理这个问题了?
(不确定:您必须自己测试 - 或者查看文档以了解这是否可以)
不过,如果您想亲自了解 HTTP 协议(protocol)的奥秘……那么,祝您好运!

关于PHP fsockopen()/fread() 返回困惑的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1279652/

相关文章:

c++ - sprintf 引起的 exc_bad_access

php - API连接到mysql有时不执行查询

PHP - 登录到 https 网站并在该 session 中获取 html 文件

php - 我如何编写两个链接到同一页面的不同工作?

PHP session 权限问题

php - 高效解析多父依赖数组

无法将缓冲区的内容复制到 C 中的字符串 : reading from . bin 文件中

c++ - 恐惧的怪异行为

php - 如何在 PHP 中将 fsockopen(或兼容)与 SOCKS 代理一起使用?

javascript - 使用 PHP 和 AJAX 提交单选按钮