PHP XML Expat Parser


내장되어 있는 Expat 파서(parser)는 PHP 에서 XML 문서를 처리할 수 있게 해준다.


What is Expat?

Expat 파서는 이벤트-기반 파서이다. 

이벤트-기반 파서는 XML 문서의 구조가 아니라, 내용에 초점을 둔다. 이 때문에, 이벤트-기반 파서는 트리-기반 파서 보다도 더 빨리 데이타에 접근할 수 있다. 

다음의 XML 부분을 보시오:

<from>Jani</from>

이벤트-기반 파서는 위의 XML을 세 가지 이벤트의 시리즈로 봅니다.:

  • 요소 시작: from
  • CDATA 섹션 시작, 값: Jani
  • 요소 닫기: from

위의 XML 예는 잘 구성된(well-formed) XML을 포함합니다. 그러나, 그와 관련된 문서 형식 정의 (Document Type Definition (DTD))가 존재하지 않기 때문에, 유효한 XML은 아닙니다. 

그러나, 이것이 Expat 파서를 사용하는 경우에는 차이가 없습니다. Expat 는 비-검증(non-validating) 파서이며, 어떤 DTDs 도 무시합니다..

이벤트-기반, 비-검증 XML 파서로써 Expat 은 빠르고, 작아서, PHP 웹 응용에 완벽히 적합합니다. 

Note: XML 문서는 잘-구성되어(well-formed)야 하며, 그렇지 않으면 Expat 는 에러를 발생 합니다.

XML Expat 파서 함수는 PHP 코어의 일부 입니다. 이 함수들을 사용하는데 어떤 설치로 필요치 않습니다. 


XML File

아래의 XML 파일 "note.xml" 은 우리의 예에서 사용될 겁니다. :

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


Initializing the XML Parser

우리는 PHP 에서 파서를 초기화 시키고,  서로 다른 XML 이벤트들을 위한 핸들러들을 정의하고 , 그리고 XML 파일을 분석하려 합니다. 

Example

<?php
//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
  {
  switch($element_name)
    {
    case "NOTE":
    echo "-- Note --<br>";
    break;
    case "TO":
    echo "To: ";
    break;
    case "FROM":
    echo "From: ";
    break;
    case "HEADING":
    echo "Heading: ";
    break;
    case "BODY":
    echo "Message: ";
    }
  }

//Function to use at the end of an element
function stop($parser,$element_name)
  {
  echo "<br>";
  }

//Function to use when finding character data
function char($parser,$data)
  {
  echo $data;
  }

//Specify element handler
xml_set_element_handler($parser,"start","stop");

//Specify data handler
xml_set_character_data_handler($parser,"char");

//Open XML file
$fp=fopen("note.xml","r");

//Read data
while ($data=fread($fp,filesize("note .xml")))
  {
  xml_parse($parser,$data,feof($fp)) or
  die (sprintf("XML Error: %s at line %d",
  xml_error_string(xml_get_error_code($parser)),
  xml_get_current_line_number($parser)));
  }

//Free the XML parser
xml_parser_free($parser);
?>

위의 코드의 출력은  다음과 같을 것이다.:

-- Note --
To: Tove
From: Jani
Heading: Reminder
Message: Don't forget me this weekend!

작동되는 방법:

  1. xml_parser_create() 함수로 XML 파서를 초기화 
  2. 서로 다른 이벤트 핸들러에 사용할 함수를 생성.
  3. 파서가 여는/닫는 태그를 만날 때 실행될 함수를 지정하기 위한 xml_set_element_handler() 함수를 추가
  4. 파서가 문자 데이타를 만날 때 실행될 함수를 지정하기 위한 xml_set_character_data_handler() 함수를 추가
  5. xml_parse() 함수로 "test.xml" 파일을 분석(Parse)
  6. 에러가 발생할 경우에, XML 에러를 텍스트 설명을로 변환해 줄 xml_error_string() 함수를 추가
  7. xml_parser_create() 함수에 할당 되었던 메모리를 해제하기 위해서 xml_parser_free() 함수를 호출 

More PHP Expat Parser

PHP Expat 함수에 대하여 더 자세한 정보를 위해서는 ==> PHP XML Parser Reference 를 방문하시오.