2023-09-23 258 View 공개 |
외부 URL의 OG(Open Graph) 태그 정보를 가져와서 반응형으로 미리보기를 생성하는 기능을 PHP로 구현하려면 몇 가지 과정이 필요합니다. 외부 URL의 HTML을 가져옵니다. 가져온 HTML에서 OG 태그 정보를 추출합니다. 추출한 정보를 바탕으로 반응형 미리보기를 생성합니다.
function getMetaData($url) { $content = file_get_contents($url); $doc = new DOMDocument(); @$doc->loadHTML($content); $xpath = new DOMXPath($doc); // OG 태그 추출 $query = '//meta[starts-with(@property, "og:")]'; $metaOg = $xpath->query($query); $tags = []; foreach ($metaOg as $tag) { $tags[str_replace('og:', '', $tag->getAttribute('property'))] = $tag->getAttribute('content'); } // Keywords 추출 $keywords = $xpath->query('//meta[@name="keywords"]/@content')->item(0); if ($keywords) { $tags['keywords'] = $keywords->value; } return $tags; } $url = "https://example.com"; // 외부 URL $tags = getMetaData($url); ?> "border: 1px solid #ccc; padding: 10px; width: 300px; max-width: 100%;"> if (isset($tags['image'])): ?> "" alt="Preview Image" style="width: 100%;"> endif; ?> echo $tags['title']; ?> echo $tags['description']; ?> Keywords: echo $tags['keywords']; ?>
위 PHP 코드는 간단하게 OG 태그 정보를 가져와서 미리보기를 생성하는 예제입니다. 실제로 프로덕션 환경에서 사용하기 위해서는 오류 처리, 보안 처리 등의 추가적인 작업이 필요합니다.