php - Curl:保存文件而不是打开文件

标签 php file curl fopen sugarcrm

我正在调用向我发送此响应的 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);

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

您是否知道可能导致此问题的原因?

提前致谢。

最佳答案

您需要为 fputs 指定内容长度以确保其二进制安全。

在这种情况下,您可以尝试 fputs($file, $content, 68720);

并最终提供标题的长度。

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

关于php - Curl:保存文件而不是打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31603825/

相关文章:

php - 使用 PHP 跨三个 MySQL 表进行更新/插入

php - 从数组php中获取第一个非空值

php - 尝试使用 Adaptive Simple Payments 但出现黑屏

PHP 警告 : PHP Startup: Unable to load dynamic library php_curl. dll 无法找到

curl - 将以下 Paypal curl 命令转换为 axios?

php - 在 Netsuite 中创建新的销售订单时如何设置 Paypal 授权 ID

php - 交响乐 2 : Using Twig extension in form builder

斯卡拉 : bug with getLines?

file - 在 ParaView 中显示高程网格

python - 异常退出期间文件是否关闭?