👾 php

php gnb 구조 불러와서 lnb스타일 브레드크럼 만들기

(。θᗨθ。) 2025. 1. 8. 11:00
<?php
// GNB DOM 구조 가져오기
ob_start();
include($_SERVER['DOCUMENT_ROOT'] . '/ko/inc/inc-gnb.php');
$gnbHtml = ob_get_clean();

// UTF-8 변환
$gnbHtml = mb_convert_encoding($gnbHtml, 'HTML-ENTITIES', 'UTF-8');

// 현재 페이지 정보
$currentUriPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$currentQuery = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
parse_str($currentQuery ?? '', $currentQueryParams);

// DOM 파싱
$dom = new DOMDocument('1.0', 'UTF-8');
libxml_use_internal_errors(true);
$dom->loadHTML($gnbHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();

// 브레드크럼 아이템 수집
$xpath = new DOMXPath($dom);
$breadcrumbItems = [];
$dep1Nodes = $xpath->query("//li[@class='gnb__list']");

foreach ($dep1Nodes as $dep1Node) {
    $dep1Link = $dep1Node->getElementsByTagName('a')[0]->getAttribute('href');
    $dep1Path = parse_url($dep1Link, PHP_URL_PATH);
    $dep2Node = $dep1Node->getElementsByTagName('ul')->item(0);

    if (!$dep2Node) continue;

    // dep1 또는 dep2 링크와 현재 URI 경로가 포함 관계인지 확인
    $matchFound = false;
    if (strpos($currentUriPath, $dep1Path) !== false) {
        $matchFound = true;
    } else {
        foreach ($dep2Node->getElementsByTagName('a') as $link) {
            if (strpos($currentUriPath, parse_url($link->getAttribute('href'), PHP_URL_PATH)) !== false) {
                $matchFound = true;
                break;
            }
        }
    }

    if ($matchFound) {
        foreach ($dep2Node->getElementsByTagName('a') as $link) {
            $breadcrumbItems[] = [
                'name' => $link->nodeValue,
                'link' => $link->getAttribute('href'),
            ];
        }
        break;
    }
}

// 브레드크럼 출력
if (!empty($breadcrumbItems)) {
    echo '<ul class="breadcrumb"><div class="inner">';
    foreach ($breadcrumbItems as $item) {
        $itemPath = parse_url($item['link'], PHP_URL_PATH);
        $pathMatch = ($currentUriPath === $itemPath);
        
        // 페이지별 활성화 조건 확인
        switch (basename($currentUriPath)) {
            case 'equipment.php':
                $isActive = $pathMatch;
                break;
            case 'board.php':
                parse_str(parse_url($item['link'], PHP_URL_QUERY) ?? '', $itemQueryParams);
                $isActive = $pathMatch && 
                           isset($currentQueryParams['bo_table'], $itemQueryParams['bo_table']) && 
                           $currentQueryParams['bo_table'] === $itemQueryParams['bo_table'];
                break;
            default:
                $isActive = $pathMatch && $_SERVER['REQUEST_URI'] === $item['link'];
        }
        
        echo '<li class="' . ($isActive ? 'on' : '') . '">';
        echo '<a href="' . htmlspecialchars($item['link']) . '">' . htmlspecialchars($item['name']) . '</a>';
        echo '</li>';
    }
    echo '</div></ul>';
} else {
    echo '<p>Breadcrumb를 찾을 수 없습니다.</p>';
}
728x90