Zend framework Zend Framework操作中文件名中的空格与readfile类似

Zend framework Zend Framework操作中文件名中的空格与readfile类似,zend-framework,readfile,Zend Framework,Readfile,我从PHP.net readfile页面抓取了以下代码: <?php // Action controller public function someAction() { $response = $this->_response; // Disable view and layout rendering $this->_helper->viewRenderer->setNoRender(); $this->_helper

我从PHP.net readfile页面抓取了以下代码:

<?php

// Action controller
public function someAction() {

    $response = $this->_response;

    // Disable view and layout rendering
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout()->disableLayout();

    // Process the file
    $file = 'whatever.zip';
    $bits = @file_get_contents($file);
    if(strlen($bits) == 0) {
        $response->setBody('Sorry, we could not find requested download file.');
    }
    else {
        $response->setHeader('Content-type', 'application/octet-stream', true);
        $response->setBody($bits);
    }
}

?>

它适用于大多数文件,但当我在文件名中有空格的文件上测试它时,它说它找不到请求的文件。有什么建议吗,或者有没有更好的方法在Zend Framework中读取文件,其中文件名可以有空格?

来自手册页面:

注意:如果您使用 特殊字符,例如空格, 您需要使用

(编辑:使用
rawurlencode()
将空格转换为
%20
,而不是
+

因此,在使用文件名之前,需要先输入文件名:

$file = rawurlencode('whatever.zip');

我用字符串替换去掉了文件名中的空格,现在它可以工作了:

$file = str_replace(" ","%20",$file);

那里没有骰子。它把+'放在名字里,我收到消息说“对不起,我们找不到请求的下载文件。”你说得对。改用
rawurlencode()
。这会将空格转换为
%20
,而不是
+
。不要使用
str_replace()
:)我也无法让rawurlencode()工作。奇怪的是,为什么不使用str_replace()?使用
str_replace()
会产生脆弱且不可维护的代码-您实际上是在编写一种手工编码空格字符的方法
rawurlencode()
将对所有非alnum字符进行编码,这样当您突然得到一个带有
@
^
字符的文件名时,您的代码不会中断。
rawurlencode()
如果在目录路径上运行,可能无法工作,因为它也会对斜杠进行编码。它设计为仅在URI的文件名部分运行。如果要从目录下载文件,只需将编码的文件名附加到目录路径。有关使用示例,请参阅PHP手册: