国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊 PHP的XML分析函數(shù)(轉)?。ń榻B這個PHP里的XML分析函數(shù)的文章可不太有哦。。 看過這篇就應該清楚點了吧...

PHP的XML分析函數(shù)(轉)?。ń榻B這個PHP里的XML分析函數(shù)的文章可不太有哦。。 看過這篇就應該清楚點了吧...

Jun 21, 2016 am 09:12 AM
element nbsp quot xml

xml|函數(shù)

PHP的XML分析函數(shù)

首先我得承認我喜歡計算機標準。如果每個人都遵從這個行業(yè)的標準,互聯(lián)網將會是一個更好的媒體。使用標準化的數(shù)據(jù)交換格式才能使開放的和獨立于平臺的計算模式切實可行。這就是我作為XML愛好者的原因。

幸運的是,我最喜愛的腳本語言不但支持XML而且對其支持正不斷加強。PHP可以讓我迅速將XML文檔發(fā)布到互聯(lián)網上,收集XML文檔的統(tǒng)計信息,將XML文檔轉換成其它格式。例如,我時常用PHP的XML處理能力來管理我用XML所寫的文章和書。

本文中,我將討論任何用PHP內建的Expat解析器來處理XML文檔。通過范例,我將演示Expat的處理方法。同時,范例可以告訴你如何:

建立你自己的處理函數(shù)??
將XML文檔轉換成你自己的PHP數(shù)據(jù)結構

介紹Expat

XML的解析器,同樣稱為XML處理器,可以使程序訪問XML文檔的結構和內容。Expat是PHP腳本語言的XML解析器。它同時也運用在其它項目中,例如Mozilla、Apache和Perl。

什么是基于事件的解析器?

XML解析器的兩種基本類型:

基于樹型的解析器:將XML文檔轉換成樹型結構。這類解析器分析整篇文章,同時提供一個API來訪問所產生樹的每個元素。其通用的標準為DOM(文檔對象模式)。??
基于事件的解析器:將XML文檔視為一系列的事件。當一個特殊事件發(fā)生時,解析器將調用開發(fā)者提供的函數(shù)來處理。??
基于事件的解析器有一個XML文檔的數(shù)據(jù)集中視圖,也就是說它集中在XML文檔的數(shù)據(jù)部分,而不是其結構。這些解析器從頭到尾處理文檔,并將類似于-元素的開始、元素的結尾、特征數(shù)據(jù)的開始等等-事件通過回調(callback)函數(shù)報告給應用程序。以下是一個"Hello-World"的XML文檔范例:

??
Hello World??
??

基于事件的解析器將報告為三個事件:

開始元素:greeting??
CDATA項的開始,值為:Hello World??
結束元素:greeting??
不像基于樹型的解析器,基于事件的解析器不產生描述文檔的結構。在CDATA項中,基于事件的解析器不會讓你得到父元素greeting的信息。
然而,它提供一個更底層的訪問,這就使得可以更好地利用資源和更快地訪問。通過這種方式,就沒有必要將整個文檔放入內存;而事實上,整個文檔甚至可以大于實際內存值。


Expat就是這樣的一種基于事件的解析器。當然如果使用Expat,必要時它一樣可以在PHP中生成完全的原生樹結構。


上面Hello-World的范例包括完整的XML格式。但它是無效的,因為既沒有DTD(文檔類型定義)與其聯(lián)系,也沒有內嵌DTD。


對于Expat,這并沒有區(qū)別:Expat是一個不檢查有效性的解析器,因此忽略任何與文檔聯(lián)系的DTD。但應注意的是文檔仍然需要完整的格式,否則Expat(和其他符合XML標準的解析器一樣)將會隨著出錯信息而停止。


作為不檢查有效性的解析器,Exapt的快速性和輕巧性使其十分適合互聯(lián)網程序。


編譯Expat

Expat可以編譯進PHP3.0.6版本(或以上)中。從Apache1.3.9開始,Expat已經作為Apache的一部分。在Unix系統(tǒng)中,通過-with-xml選項配置PHP,你可以將其編譯入PHP。


如果你將PHP編譯為Apache的模塊,而Expat將默認作為Apache的一部分。在Windows中,你則必須要加載XML動態(tài)連接庫。

XML范例:XMLstats

了解Expat的函數(shù)的一個辦法就是通過范例。我們所要討論的范例是使用Expat來收集XML文檔的統(tǒng)計數(shù)據(jù)。


對于文檔中每個元素,以下信息都將被輸出:

該元素在文檔中使用的次數(shù)??
該元素中字符數(shù)據(jù)的數(shù)量??
元素的父元素??
元素的子元素??
注意:為了演示,我們利用PHP來產生一個結構來保存元素的父元素和子元素

準備

用于產生XML解析器實例的函數(shù)為xml_parser_create()。該實例將用于以后的所有函數(shù)。這個思路非常類似于PHP中MySQL函數(shù)的連接標記。在解析文檔前,基于事件的解析器通常要求你注冊回調函數(shù)-用于特定的事件發(fā)生時調用。Expat沒有例外事件,它定義了如下七個可能事件:


對象 XML解析函數(shù) 描述

元素 xml_set_element_handler() 元素的開始和結束

字符數(shù)據(jù) xml_set_character_data_handler() 字符數(shù)據(jù)的開始

外部實體 xml_set_external_entity_ref_handler() 外部實體出現(xiàn)

未解析外部實體 xml_set_unparsed_entity_decl_handler() 未解析的外部實體出現(xiàn)

處理指令 xml_set_processing_instruction_handler() 處理指令的出現(xiàn)

記法聲明 xml_set_notation_decl_handler() 記法聲明的出現(xiàn)

默認 xml_set_default_handler() 其它沒有指定處理函數(shù)的事件

所有的回調函數(shù)必須將解析器的實例作為其第一個參數(shù)(此外還有其它參數(shù))。


對于本文最后的范例腳本。你需要注意的是它既用到了元素處理函數(shù)又用到了字符數(shù)據(jù)處理函數(shù)。元素的回調處理函數(shù)通過xml_set_element_handler()來注冊。


這個函數(shù)需要三個參數(shù):

解析器的實例??
處理開始元素的回調函數(shù)的名稱??
處理結束元素的回調函數(shù)的名稱??
當開始解析XML文檔時,回調函數(shù)必須存在。它們必須定義為與PHP手冊中所描述的原型一致。


例如,Expat將三個參數(shù)傳遞給開始元素的處理函數(shù)。在腳本范例中,其定義如下:


function start_element($parser, $name, $attrs)??


第一個參數(shù)是解析器標示,第二個參數(shù)是開始元素的名稱,第三參數(shù)為包含元素所有屬性和值的數(shù)組。


一旦你開始解析XML文檔,Expat在遇到開始元素是都將調用你的start_element()函數(shù)并將參數(shù)傳遞過去。


XML的Case Folding選項

用xml_parser_set_option()函數(shù)將Case folding選項關閉。這個選項默認是打開的,使得傳遞給處理函數(shù)的元素名自動轉換為大寫。但XML對大小寫是敏感的(所以大小寫對統(tǒng)計XML文檔是非常重要的)。對于我們的范例,case folding選項必須關閉。


解析文檔

在完成所有的準備工作后,現(xiàn)在腳本終于可以解析XML文檔:

Xml_parse_from_file(),一個自定義的函數(shù),打開參數(shù)中指定的文件,并以4kb的大小進行解析??
xml_parse()和xml_parse_from_file()一樣,當發(fā)生錯誤時,即XML文檔的格式不完全時,將會返回false。??
你可以使用xml_get_error_code()函數(shù)來得到最后一個錯誤的數(shù)字代碼。將此數(shù)字代碼傳遞給xml_error_string()函數(shù)即可得到錯誤的文本信息。??
輸出XML當前的行數(shù),使得調試更容易。??
在解析的過程中,調用回調函數(shù)。??
描述文檔結構

當解析文檔時,對于Expat需要強調問題的是:如何保持文檔結構的基本描述?


如前所述,基于事件的解析器本身并不產生任何結構信息。


不過標簽(tag)結構是XML的重要特性。例如,元素序列表示的意思不同于<figure><title>。也就是說,任何作者都會告訴你書名和圖名是沒有關系的,雖然它們都用到"title"這個術語。因此,為了更有效地使用基于事件的解析器處理XML,你必須使用自己的棧(stacks)或列表(lists)來維護文檔的結構信息。 <br><br><br>為了產生文檔結構的鏡像,腳本至少需要知道目前元素的父元素。用Exapt的API是無法實現(xiàn)的,它只報告目前元素的事件,而沒有任何前后關系的信息。因此,你需要建立自己的棧結構。 <br><br><br>腳本范例使用先進后出(FILO)的棧結構。通過一個數(shù)組,棧將保存全部的開始元素。對于開始元素處理函數(shù),目前的元素將被array_push()函數(shù)推到棧的頂部。相應的,結束元素處理函數(shù)通過array_pop()將最頂?shù)脑匾谱摺?<br><br><br>對于序列<book><title>,棧的填充如下:

開始元素book:將"book"賦給棧的第一個元素($stack[0])。??
開始元素title:將"title"賦給棧的頂部($stack[1])。??
結束元素title:從棧中將最頂部的元素移去($stack[1])。??
結束元素title:從棧中將最頂部的元素移去($stack[0])。??
PHP3.0通過一個$depth變量手動控制元素的嵌套來實現(xiàn)范例。這就使腳本看起來比較復雜。PHP4.0通過array_pop()和array_push()兩個函數(shù)來使腳本看起來更簡潔。


收集數(shù)據(jù)

為了收集每個元素的信息,腳本需要記住每個元素的事件。通過使用一個全局的數(shù)組變量$elements來保存文檔中所有不同的元素。數(shù)組的項目是元素類的實例,有4個屬性(類的變量)

$count -該元素在文檔中被發(fā)現(xiàn)的次數(shù)??
$chars -元素中字符事件的字節(jié)數(shù)??
$parents -父元素??
$childs - 子元素??
正如你所看到的,將類實例保存在數(shù)組中是輕而易舉的。


注意:PHP的一個特性是你可以通過while(list() = each())loop遍歷整個類結構,如同你遍歷整個相應的數(shù)組一樣。所有的類變量(當你用PHP3.0時還有方法名)都以字符串的方式輸出。


當發(fā)現(xiàn)一個元素時,我們需要增加其相應的記數(shù)器來跟蹤它在文檔中出現(xiàn)多少次。在相應的$elements項中的記數(shù)元素也要加一。


我們同樣要讓父元素知道目前的元素是它的子元素。因此,目前元素的名稱將會加入到父元素的$childs數(shù)組的項目中。最后,目前元素應該記住誰是它的父元素。所以,父元素被加入到目前元素$parents數(shù)組的項目中。


顯示統(tǒng)計信息

剩下的代碼在$elements數(shù)組和其子數(shù)組中循環(huán)顯示其統(tǒng)計結果。這就是最簡單的嵌套循環(huán),盡管輸出正確的結果,但代碼既不簡潔又沒有任何特別的技巧,它僅僅是一個你可能每天用他來完成工作的循環(huán)。


腳本范例被設計為通過PHP的CGI方式的命令行來調用。因此,統(tǒng)計結果輸出的格式為文本格式。如果你要將腳本運用到互聯(lián)網上,那么你需要修改輸出函數(shù)來產生HTML格式。

總結

Exapt是PHP的XML解析器。作為基于事件的解析器,它不產生文檔的結構描述。但通過提供底層訪問,這就使得可以更好地利用資源和更快地訪問。


作為一個不檢查有效性的解析器,Expat忽略與XML文檔連接的DTD,但如果文檔的格式不完整,它將會隨著出錯信息而停止。


提供事件處理函數(shù)來處理文檔??
建立自己的事件結構例如棧和樹來獲得XML結構信息標記的優(yōu)點。??
每天都有新的XML程序出現(xiàn),而PHP對XML的支持也不斷加強(例如,增加了支持基于DOM的XML解析器LibXML)。


有了PHP和Expat,你就可以為即將出現(xiàn)的有效、開放和獨立于平臺的標準作準備。

范例

??
/*****************************************************************************??
* 名稱:XML解析范例:XML文檔信息統(tǒng)計
* 描述??
* 本范例通過PHP的Expat解析器收集和統(tǒng)計XML文檔的信息(例如:每個元素出現(xiàn)的次數(shù)、父元素和子元素??
* XML文件作為一個參數(shù) ./xmlstats_PHP4.php3 test.xml??
* $Requires: Expat 要求:Expat PHP4.0編譯為CGI模式??
*****************************************************************************/??

// 第一個參數(shù)是XML文件
$file = $argv[1];??

// 變量的初始化
$elements = $stack = array();??
$total_elements = $total_chars = 0;??

// 元素的基本類
class element??
{??
var $count = 0;??
var $chars = 0;??
var $parents = array();??
var $childs = array();??
}??

// 解析XML文件的函數(shù)
function xml_parse_from_file($parser, $file)??
{??
if(!file_exists($file))??
{??
die("Can't find file \"$file\".");??
}??

if(!($fp = @fopen($file, "r")))??
{??
die("Can't open file \"$file\".");??
}??

while($data = fread($fp, 4096))??
{??
if(!xml_parse($parser, $data, feof($fp)))??
{??
return(false);??
}??
}??

fclose($fp);??

return(true);??
}??

// 輸出結果函數(shù)(方框形式)
function print_box($title, $value)??
{??
printf("\n+%'-60s+\n", "");??
printf("|%20s", "$title:");??
printf("%14s", $value);??
printf("%26s|\n", "");??
printf("+%'-60s+\n", "");??
}??

// 輸出結果函數(shù)(行形式)
function print_line($title, $value)??
{??
printf("%20s", "$title:");??
printf("%15s\n", $value);??
}??

// 排序函數(shù)
function my_sort($a, $b)??
{??
return(is_object($a) && is_object($b) ? $b->count - $a->count: 0);??
}??

function start_element($parser, $name, $attrs)??
{??
global $elements, $stack;??

// 元素是否已在全局$elements數(shù)組中?
if(!isset($elements[$name]))??
{??
// 否-增加一個元素的類實例
$element = new element;??
$elements[$name] = $element;??
}??

// 該元素的記數(shù)器加一
$elements[$name]->count++;??

// 是否有父元素?
if(isset($stack[count($stack)-1]))??
{??
// 是-將父元素賦給$last_element
$last_element = $stack[count($stack)-1];??

// 如果目前元素的父元素數(shù)組為空,初始化為0
if(!isset($elements[$name]->parents[$last_element]))??
{??
$elements[$name]->parents[$last_element] = 0;??
}??

// 該元素的父元素記數(shù)器加一
$elements[$name]->parents[$last_element]++;??

// 如果目前元素的父元素的子元素數(shù)組為空,初始化為0

if(!isset($elements[$last_element]->childs[$name]))??
{??
$elements[$last_element]->childs[$name] = 0;??
}??

// 該元素的父元素的子元素記數(shù)器加一
$elements[$last_element]->childs[$name]++;??
}??

// 將目前的元素加入到棧中
array_push($stack, $name);??
}??

function stop_element($parser, $name)??
{??
global $stack;??

// 從棧中將最頂部的元素移去
array_pop($stack);??
}??

function char_data($parser, $data)??
{??
global $elements, $stack, $depth;??

// 增加目前元素的字符數(shù)目
$elements[$stack][count($stack)-1]]->chars += strlen(trim($data));??
}??

// 產生解析器的實例
$parser = xml_parser_create();??

// 設置處理函數(shù)
xml_set_element_handler($parser, "start_element", "stop_element");??
xml_set_character_data_handler($parser, "char_data");??
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);??

// 解析文件
$ret = xml_parse_from_file($parser, $file);??
if(!$ret)??
{??
die(sprintf("XML error: %s at line %d",??
xml_error_string(xml_get_error_code($parser)),??
xml_get_current_line_number($parser)));??
}??

// 釋放解析器
xml_parser_free($parser);??

// 釋放協(xié)助元素
unset($elements["current_element"]);??
unset($elements["last_element"]);??

// 根據(jù)元素的次數(shù)排序
uasort($elements, "my_sort");??

// 在$elements中循環(huán)收集元素信息
while(list($name, $element) = each($elements))??
{??
print_box("Element name", $name);??

print_line("Element count", $element->count);??
print_line("Character count", $element->chars);??

printf("\n%20s\n", "* Parent elements");??

// 在該元素的父中循環(huán),輸出結果
while(list($key, $value) = each($element->parents))??
{??
print_line($key, $value);??
}??
if(count($element->parents) == 0)??
{??
printf("%35s\n", "[root element]");??
}??

// 在該元素的子中循環(huán),輸出結果
printf("\n%20s\n", "* Child elements");??
while(list($key, $value) = each($element->childs))??
{??
print_line($key, $value);??
}??
if(count($element->childs) == 0)??
{??
printf("%35s\n", "[no childs]");??
}??

$total_elements += $element->count;??
$total_chars += $element->chars;??
}??

// 最終結果
print_box("Total elements", $total_elements);??
print_box("Total characters", $total_chars);??
?>?



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

How to modify element.style How to modify element.style Nov 24, 2023 am 11:15 AM

Methods for element.style to modify elements: 1. Modify the background color of the element; 2. Modify the font size of the element; 3. Modify the border style of the element; 4. Modify the font style of the element; 5. Modify the horizontal alignment of the element. Detailed introduction: 1. Modify the background color of the element, the syntax is "document.getElementById("myElement").style.backgroundColor = "red";"; 2. Modify the font size of the element, etc.

See all articles