通过 xml_parser_create() 函数初始化 XML 解析器
创建配合不同事件处理程序的的函数

添加 xml_set_element_handler() 函数来定义,当解析器遇到开始和结束标签时执行哪个函数

添加 xml_set_character_data_handler() 函数来定义,当解析器遇到字符数据时执行哪个函数
通过 xml_parse() 函数来解析文件 “test.xml”

万一有错误的话,添加 xml_error_string() 函数把 XML 错误转换为文本说明

调用 xml_parser_free() 函数来释放分配给 xml_parser_create() 函数的内存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?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文件:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

以上XML的输出:

1
2
3
4
5
-- Note --
To: George
From: John
Heading: Reminder
Message: Don't forget the meeting!

XML Dom

输出XML文件内容到浏览器(原封不动)
标签会当作HTML标签,隐藏

1
2
3
4
5
6
7
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>
saveXML() 函数把内部 XML 文档放入一个字符串,这样我们就可以输出它。
1
2
3
4
5
6
7
8
9
10
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br />";
}
?>

以上代码的输出:

1
2
3
4
5
6
7
8
9
#text =
to = George
#text =
from = John
#text =
heading = Reminder
#text =
body = Don't forget the meeting!
#text =

当 XML 生成时,它通常会在节点之间包含空白。
XML DOM 解析器把它们当作普通的元素,如果您不注意它们,有时会产生问题。


SimpleXML

1
2
3
4
5
6
7
8
9
10
<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>

以上代码的输出:

1
2
3
4
5
note
to: George
from: John
heading: Reminder
body: Don't forget the meeting!