본문 바로가기
노코드 No Code

[PHP] 헤더 meta 태그 가져오기

by 웹디자인 2022. 9. 30.

사이트를 제작하다보면 meta tag 정보를 필요로 할때가 있습니다.

페이지 제목, 내용, 이미지 등 주요 정보는 특히 페이지 공유를 위해서는 필수적인 요소입니다.

카카오톡을 통해 주소를 입력하면 페이지 정보가 미리 보여지는 것이 대표적인 예라고 하겠습니다.

 

 

<?php 
 
// 웹사이트 주소
$url = 'https://www.sitename.com/'; 
 
// Extract HTML using curl 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
 
$data = curl_exec($ch); 
curl_close($ch); 
 
// Load HTML to DOM object 
$dom = new DOMDocument(); 
@$dom->loadHTML($data); 
 
// Parse DOM to get Title data 
$nodes = $dom->getElementsByTagName('title'); 
$title = $nodes->item(0)->nodeValue; 
 
// Parse DOM to get meta data 
$metas = $dom->getElementsByTagName('meta'); 
 
$description = $keywords = ''; 
for($i=0; $i<$metas->length; $i++){ 
    $meta = $metas->item($i); 
     
    if($meta->getAttribute('name') == 'description'){ 
        $description = $meta->getAttribute('content'); 
    } 
     
    if($meta->getAttribute('name') == 'keywords'){ 
        $keywords = $meta->getAttribute('content'); 
    } 
} 
 
echo "Title: $title". '<br/>'; 
echo "Description: $description". '<br/>'; 
echo "Keywords: $keywords"; 
 
?>

 

댓글