2009-06-17 9 views
10

curlとPHPを使用してファイルを保存するにはどうすればよいですか?curlとPHPを使用したファイルの保存

+2

はあなたがカール必要よろしいですか? file_get_contents( "http://whatever.com")で十分ではありませんか? –

+1

14,000ビューのうち50%以上が 'file_get_contents'が十分でなかったと確信しています – redolent

答えて

8

あなたは使用することができます。

<?php 
// create a new cURL resource 
$ch = curl_init(); 

// set URL and other appropriate options 
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 0); 

// grab URL and pass it to the browser 
$out = curl_exec($ch); 

// close cURL resource, and free up system resources 
curl_close($ch); 


$fp = fopen('data.txt', 'w'); 
fwrite($fp, $out); 
fclose($fp); 

?> 

参照:http://jp2.php.net/manual/en/function.curl-exec.phphttp://us3.php.net/manual/en/function.fwrite.php

+2

これは小さなファイルの仕事をしますが、保存する前にファイル全体をメモリにロードするので、ファイルがPHPのメモリ制限より大きい場合は、メモリ不足エラーが発生します。 Haim Evgiの答えは、ファイルをこの問題を回避するディスクに正しくストリームします。 –

+0

'curl_exec'を' file_put_contents() 'にまっすぐにします。少なくとも、3行のコードを保存します。 –

22

は、あなたがこのような何かをしたいのですか?

function get_file($file, $local_path, $newfilename) 
{ 
    $err_msg = ''; 
    echo "<br>Attempting message download for $file<br>"; 
    $out = fopen($local_path.$newfilename,"wb"); 
    if ($out == FALSE){ 
     print "File not opened<br>"; 
     exit; 
    } 

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_FILE, $out); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_URL, $file); 

    curl_exec($ch); 
    echo "<br>Error is : ".curl_error ($ch); 

    curl_close($ch); 
    //fclose($handle); 

}//end function 

機能: その機能と三つのパラメータ

get_file($file, $local_path, $newfilename) 

$fileを受け入れるは:

$local_pathを検索対象のファイル名である:ディレクトリへのローカルパスを記憶することですオブジェクト

$newfilename:はローカルシステムの新しいファイル名です

-3

curlには、stdoutではなくファイルに出力を書き込む-oオプションがあると思います。

-oの後に出力ファイルの名前を指定する必要があります。

例:

 

curl -o path_to_the_file url 
+1

これはcurlの*コマンドライン*バージョンですが、PHPのcurlライブラリではありません。 –

関連する問題