LoginSignup
7
7

More than 5 years have passed since last update.

phpでfile_get_contentsからcurlに移行する

Posted at

file_get_contents() のメリット・デメリット

気軽にURLを指定してその内容を取得してくれる便利な関数で、簡単に実装できるというメリットがある。だが、思ったどおりタイムアウト時間を指定できないことがあるので、なるべく使わないようにしたい。

file_get_contents()
$url = htmlspecialchars_decode("http://api.hoge.com/1/api.php");
$json = file_get_contents($url);

curl のメリット

タイムアウト時間を細かく指定できる。file_get_contentsのようにタイムアウト時間が思った通り動かないことはないので、可用性や完全性を求める必要があるものには必須だ。

移行する

file_get_contents()
$url = htmlspecialchars_decode("http://api.hoge.com/1/api.php");
$json = json_decode(file_get_contents($url),true);

以上のコードがあったとすると、以下のcurlに置き換えられる。

curl
$url = "http://api.hoge.com/1/api.php"; //URLを指定
$ch = curl_init(htmlspecialchars_decode($url));
$options = array(CURLOPT_RETURNTRANSFER => 1,
                 CURLOPT_TIMEOUT => 3 //タイムアウトするまでの時間
                );

curl_setopt_array($ch,$option);

$json_data = curl_exec($ch);
$json = json_decode($json_data,true);

file_get_contents()を使用していたらタイムアウト処理がうまくできなかったので、移行してみた。
もしもっと良い方法や美しい書き方があればコメントで教えてください!

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7