PHP 新手入門之XML解析器
XML Parser
所有現代瀏覽器都有內建的 XML 解析器。
XML 解析器把 XML 文檔轉換為 XML DOM 對象 - 可通過 JavaScript 操作的對象
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
接下來我們寫一個php的文件來對上面代碼進行操作
<?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("test.xml","r"); //Read data while ($data=fread($fp,4096)){ 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); ?>
工作原理:
通過 xml_parser_create() 函數初始化 XML 解析器
創(chuàng)建配合不同事件處理程序的的函數
添加 xml_set_element_handler() 函數來定義,當解析器遇到開始和結束標簽時執(zhí)行哪個函數
添加 xml_set_character_data_handler() 函數來定義,當解析器遇到字符數據時執(zhí)行哪個函數
通過 xml_parse() 函數來解析文件 "test.xml"
萬一有錯誤的話,添加 xml_error_string() 函數把 XML 錯誤轉換為文本說明
調用 xml_parser_free() 函數來釋放分配給 xml_parser_create() 函數的內存