PHP | cURL 사용방법, (GET, POST)

|

설치

sudo apt install php-curl

cURL은 설치를 해야 사용할 수 있습니다.
만약 설치되지 않았다면 Call to undefined function curl_init() 에러가 나게 됩니다.

사용법

// 리소스 초기화
$ch = curl_init();

// 사이트 주소
$url = "https://www.light-coding.com"

// 옵션값 설정
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 데이터 요청
$return = curl_exec($ch);

echo $return;

// 리소스 해제
curl_close($ch);

  1. curl_init() 을 활용하여 리소스를 초기화합니다.
  2. 사이트 주소를 입력합니다.
  3. curl_setopt 를 사용하여 옵션을 설정합니다.
    1. CURLOPT_URL = 주소값 전송
    2. CURLOPT_RETURNTRANSFER = True 설정시 문자열로 반환
  4. 데이터를 요청합니다.
  5. 마지막으로 curl 을 종료합니다.

인코딩, 디코딩

  • json_encode($return, true);
  • json_decode($return, true); : json 반환값을 PHP 에서 읽을 수 있게 변환할 수 있습니다.

header 설정

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'User-Agent: Mozilla/5.0',
  'Referer: https://www.light-coding.com/'
));

HTTP 요청을 보냈을 때 헤더 정보를 포함시켜 전송할 수 있습니다.

API 요청 사용법

<!-- 공휴일 정보 -->
<?php

$ch = curl_init();
$url = 'http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo'; /*URL*/
$queryParams = '?' . urlencode('ServiceKey') . '보안키입력'; /*Service Key*/
$queryParams .= '&' . urlencode('solYear') . '=' . urlencode(date('Y', time())); /**/
$queryParams .= '&' . urlencode('solMonth') . '=' . urlencode(date('m', time())); /**/


curl_setopt($ch, CURLOPT_URL, $url . $queryParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = simplexml_load_string(curl_exec($ch))->body->items;
curl_close($ch);

$dayOff = 0;

foreach ($response->item as $countDate) {

    if ($countDate->locdate[0] == date('Ymd', time())) {
        // echo "쉬는날" . "<br>";
        $dayOff = 1;
    } else {
        // echo "쉬지 않는 날" . "<br>";
    }
};

날씨정보를 변환할 수 있는 방법입니다.

PHP 에서 값 출력하기

/* curl 값 가져오기 */
$reqParam = json_decode(file_get_contents('php://input'), true);

/* 테스트 */
//echo "<pre>";
//print_r($reqParam);
//echo "</pre>";

참조

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

클릭하여 복사