현재 위치: > 최신 기사 목록> XML_PARSE에서 중첩 된 XML 문서를 재귀 적으로 구문 분석하는 방법

XML_PARSE에서 중첩 된 XML 문서를 재귀 적으로 구문 분석하는 방법

M66 2025-05-12

PHP에서 XML 문서와 함께 작업 할 때 XML_PARSE () 는 낮지 만 강력한 기능입니다. 이벤트 중심 구문 분석 모델에 의존하므로 문서의 시작, 끝 및 문자 데이터에 응답하려면 해당 콜백 기능을 등록해야합니다.

그러나 복잡한 구조를 가진 중첩 된 XML 문서에 직면하여 재귀를 사용하면 데이터 처리가보다 직관적이고 명확하게 만들 수 있습니다. 이 기사는 재귀 및 XML_PARSE () 와 함께 중첩 된 XML 데이터를 구문 분석하는 방법을 소개합니다.

1. 샘플 XML 데이터

 <catalog>
    <book id="1">
        <title>PHP Basics</title>
        <author>John Doe</author>
    </book>
    <book id="2">
        <title>Advanced PHP</title>
        <author>Jane Smith</author>
    </book>
</catalog>

2. 파서를 만들고 처리 기능을 설정하십시오

먼저 파서를 만들고 세 가지 콜백 함수를 설정해야합니다.

  • startElement () : 파서가 시작 태그를 만날 때 호출;

  • EndElement () : 파서가 엔드 태그를 만날 때 호출;

  • 문자 data () : 파서가 태그에서 텍스트를 만날 때 호출됩니다.

3. 재귀 구조 구현의 키 : 트리와 같은 어레이 구축

다음은 완전한 코드 예입니다.

 <?php

$xml = <<<XML
<catalog>
    <book id="1">
        <title>PHP Basics</title>
        <author>John Doe</author>
    </book>
    <book id="2">
        <title>Advanced PHP</title>
        <author>Jane Smith</author>
    </book>
</catalog>
XML;

$parser = xml_parser_create();
$dataStack = [];
$currentData = null;

// 태그 시작
function startElement($parser, $name, $attrs) {
    global $dataStack, $currentData;

    $element = [
        'tag' => $name,
        'attributes' => $attrs,
        'children' => [],
        'value' => ''
    ];

    if ($currentData !== null) {
        array_push($dataStack, $currentData);
    }

    $currentData = $element;
}

// 엔드 태그
function endElement($parser, $name) {
    global $dataStack, $currentData;

    if (!empty($dataStack)) {
        $parent = array_pop($dataStack);
        $parent['children'][] = $currentData;
        $currentData = $parent;
    }
}

// 텍스트 내용
function characterData($parser, $data) {
    global $currentData;

    if (isset($currentData['value'])) {
        $currentData['value'] .= trim($data);
    }
}

xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "characterData");

if (!xml_parse($parser, $xml, true)) {
    die(sprintf("XML 실수: %s 에서 %d 좋아요",
        xml_error_string(xml_get_error_code($parser)),
        xml_get_current_line_number($parser)));
}

xml_parser_free($parser);

// 최종 구조를 인쇄하십시오
print_r($currentData);
?>

4. 출력 구조 설명

구문 분석 후 다음과 유사한 중첩 어레이 구조를 얻게됩니다.

 Array
(
    [tag] => CATALOG
    [attributes] => Array()
    [children] => Array
        (
            [0] => Array
                (
                    [tag] => BOOK
                    [attributes] => Array ( [ID] => 1 )
                    [children] => Array
                        (
                            [0] => Array ( [tag] => TITLE [value] => PHP Basics )
                            [1] => Array ( [tag] => AUTHOR [value] => John Doe )
                        )
                )
            [1] => Array
                (
                    [tag] => BOOK
                    [attributes] => Array ( [ID] => 2 )
                    [children] => Array
                        (
                            [0] => Array ( [tag] => TITLE [value] => Advanced PHP )
                            [1] => Array ( [tag] => AUTHOR [value] => Jane Smith )
                        )
                )
        )
)

5. 구문 분석 구조를 JSON 또는 기타 형식으로 변환합니다

프론트 엔드 호출 또는 인터페이스 출력을 위해 위의 배열 구조를 JSON으로 쉽게 변환 할 수 있습니다.

 echo json_encode($currentData, JSON_PRETTY_PRINT);

육. 팁

  • XML 문서가 https://m66.net/data/books.xml 과 같은 네트워크에서 나오면 file_get_contents ()를 사용하여 얻을 수 있습니다.