LoginSignup
12
12

More than 5 years have passed since last update.

PHP curlでjsonとってくるヤツ

Last updated at Posted at 2013-09-04

file_get_contents()でもいいんだろうけど。。。
エラーとか細かく取れそうなので。

function getJson($url) {

  if (empty($url)) {
    $error = "Internal error";
    throw new Exception($error);
  }

  try{
    // セッションを初期化
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    // 転送を実行
    $json = curl_exec($ch);

    // エラー番号を取得
    $curlErrno = curl_errno($ch);
    if($curlErrno){
      $curlError = curl_error($ch);
      throw new Exception($curlError);
    }

    // セッションを終了
    curl_close($ch);

  } catch (Exception $e) {
    echo "Exception-".$e->getMessage();
  }

  return $json;

}

12
12
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
12
12