복붙노트

PHP 다른 페이지 컨텐츠 가져오기

PHP

PHP 다른 페이지 컨텐츠 가져오기

PHP에서 다른 웹 페이지를 실행시킨 다음 그 내용을 가지고 오고 싶을 때가 있습니다.
그럴때는 file_get_contents 함수를 사용합니다.

get 요청

$result = file_get_contents("http://주소?p1=a&p2=2");  

post 요청

post 요청은 조금 더 복잡해서 context를 만들어 줘야 합니다.

function get_contents($url, $data){  
$options = array(  
'http' => array(  
'header'  => "Content-type: application/x-www-form-urlencoded\r\n",  
'method'  => 'POST',  
'content' => http_build_query($data)  
)  
);  
$context  = stream_context_create($options);  
$result = file_get_contents($url, false, $context);  
return $result;  
}  

// 사용하기  
$url = "http://주소?p1=a&p2=2";  
$data = array('p1'=>'param 1', 'p2'=>'param 2');  
$result = get_contents($url, $data);  

if ($result){ // 만약 get_contents 가 실패하면 false를 리턴합니다.  
// 뭔가 여기서 하세요.  
}  

get 요청과 post 요청을 합치기

get 일때는 내장 함수인 file_get_contents 를, post 일 때는 우리가 만든 함수인 get_contents 를 쓰려니 불편합니다.
그래서 함수 하나로 통합해 봅시다.

function get_contents($url, $data){  
if (count($data) === 0){  
return file_get_contents($url);  
}  

$options = array(  
'http' => array(  
'header'  => "Content-type: application/x-www-form-urlencoded\r\n",  
'method'  => 'POST',  
'content' => http_build_query($data)  
)  
);  
$context  = stream_context_create($options);  
$result = file_get_contents($url, false, $context);  
return $result;  
}  

// 사용하기  
$url = "http://주소?p1=a&p2=2";  
$data = array('p1'=>'param 1', 'p2'=>'param 2');  
$result = get_contents($url, $data);  

if ($result){ // 만약 get_contents 가 실패하면 false를 리턴합니다.  
// 뭔가 여기서 하세요.  
}