代码之家  ›  专栏  ›  技术社区  ›  Elzo Valugi

如何使用Zend\u Http\u客户端或其他库下载文件

  •  1
  • Elzo Valugi  · 技术社区  · 14 年前

    而不是从流中读取并写入另一个文件,但我不确定这是否可行。

    有什么建议吗?

    4 回复  |  直到 14 年前
        1
  •  3
  •   Elzo Valugi    14 年前

    我还发现 copy 它允许将一个文件从一个url直接复制到您的磁盘上,并且是一个单行程序,不需要curl的复杂性,也不需要创建一个空文件来传输file\u get\u contents的内容。

    copy($file_url, $localpath);
    
        2
  •  1
  •   aercolino    14 年前

    file_put_contents($local_path,file_get_contents($file_url));

    也是一行;-)

    http://www.php.net/manual/en/function.copy.php#88520

    需要一些测试。。。

        3
  •  1
  •   Benjamin Cremer    14 年前

    CURLOPT_FILE curl_setopt ).

    /**
     * @param string $url
     * @param string $destinationFilePath
     * @throws Exception
     * @return string
     */
    protected function _downloadFile($url, $destinationFilePath)
    {
        $fileHandle = fopen($destinationFilePath, 'w');
    
        if (false === $fileHandle) {
            throw new Exception('Could not open filehandle');
        }
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FILE, $fileHandle);
    
        $result = curl_exec($ch);
        curl_close($ch);
        fclose($fileHandle);
    
        if (false === $result) {
            throw new Exception('Could not download file');
        }
    
        return $destinationFilePath;
    }
    


    exec() system()

    exec('wget http://google.de/ -O google.html -q') 
    

    编辑以供以后参考:

    <?php
    function downloadCurl($url, $destinationFilePath)
    {
        $fileHandle = fopen($destinationFilePath, 'w');
    
        if (false === $fileHandle) {
            throw new Exception('Could not open filehandle');
        }
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FILE, $fileHandle);
    
        $result = curl_exec($ch);
        curl_close($ch);
        fclose($fileHandle);
    
        if (false === $result) {
            throw new Exception('Could not download file');
        }
    }
    
    
    function downloadCopy($url, $destinationFilePath)
    {
        if (false === copy($url, $destinationFilePath)) {
            throw new Exception('Could not download file');
        }
    }
    
    function downloadExecWget($url, $destinationFilePath)
    {
        $output = array();
        $return = null;
        exec(sprintf('wget %s -O %s -q', escapeshellarg($url), escapeshellarg($destinationFilePath)), $output, $return);
    
        if (1 === $return) {
            throw new Exception('Could not download file');
        }
    }
    

    这三种方法的运行时和内存使用率几乎相等。

        4
  •  0
  •   Riba    14 年前
    $c = file_get_contents('http://www.example.com/my_file.tar.gz');
    

    现在将$c写入本地文件。。。