【问题标题】:Curl: Saving a file instead of opening itCurl:保存文件而不是打开它
【发布时间】:2015-07-24 06:39:31
【问题描述】:

我正在调用一个向我发送此响应的 API:

HTTP/1.1 200 OK\r\n
Date: Fri, 24 Jul 2015 06:30:16 GMT\r\n
Server: Apache/2.2.26 (Unix) mod_ssl/2.2.26 OpenSSL/0.9.8e-fips-rhel5 mod_mono/2.6.3 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 PHP/5.4.22 mod_perl/2.0.6 Perl/v5.8.8\r\n
X-Powered-By: PHP/5.4.22\r\n
Expires: \r\n
Cache-Control: max-age=0, private\r\n
Pragma: \r\n
Content-Disposition: attachment; filename="LVDox-Master.docx"\r\n
X-Content-Type-Options: nosniff\r\n
ETag: d41d8cd98f00b204e9800998ecf8427e\r\n
Content-Length: 68720\r\n
Vary: Accept-Encoding,User-Agent\r\n
Connection: close\r\n
Content-Type: application/octet-stream\r\n
\r\n
PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!\x000\x1FÎò¡\x01\x00\x00ß\x08\x00\x00\x13\x00\x08\x02[Content_Types].xml ¢\x04\x02( \x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\
...
... (etc)

如果我使用此代码,文件将发送给用户并且一切正常:

list($headers, $content) = explode("\r\n\r\n", $result ,2);
foreach (explode("\r\n",$headers) as $header)
{
    header($header);
}

//return the nonheader data
return trim($content);

但现在,我想将文件保存在其他地方,以便我的脚本可以处理它(重命名等),所以我不想直接将它发送给用户。

我尝试评论 header($header); 部分,并执行以下操作:

$content = getMyFile();
$file = fopen('MYTEST.docx', "w+");
fputs($file, $content);
fclose($file);

但生成的文件不可读(似乎已损坏)。

您知道导致此问题的原因吗?

提前致谢。

【问题讨论】:

  • 数据是否写入文件位置?即,您能否检查写入的字节数是否符合您的预期,或者它没有写入任何内容?
  • 是的,我有一个大小为 69KB 的文件。但是这个文件不正确(无法打开)。但是如果我保留标题,一切正常,但文件会发送给用户。所以标题可能很重要?
  • 尝试使用fwrite 而不是fputs - 因为您正在处理二进制数据。或者,为什么不只是file_put_contents
  • fwrite 和 file_put_contents 有同样的问题

标签: php file curl fopen sugarcrm


【解决方案1】:

您需要为 fputs 指定内容长度以使其成为二进制安全的。

这种情况你可以试试fputs($file, $content, 68720);

并最终提供标头的长度。

另外,我建议使用fopen('MYTEST.docx', "wb"); 以二进制模式打开文件,尤其是在您在 Windows 上运行代码的情况下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多