本例中的php文件讀取、顯示xml文件內容
以下為php文件的內容,把該php文件和slashdot.xml放在同一個文件夾即可
<?php
$open_tags = array(
'story' => '<story>',
'title' => '<title>',
'url' => '<url>',
'author'=> '<author>'
);
$close_tags = array(
'story' => '</story>',
'title' => '</title>',
'url' => '</url>',
'author'=> '</author>'
);
?>
<?php
//下面就是定義函數來提取數據:
// 處理開始標記的屬性指
// $attrs是一個多維數組,鍵值為屬性名, 值就是該屬性的值
function startelement($parser, $name, $attrs=''){
global $open_tags, $temp, $current_tag;
$current_tag = $name;
if ($format = $open_tags[$name]){
switch($name){
case 'story':
echo '新的故事: ';
break;
default:
break;
}
}
}
// $current_tag告訴我們正在處理的標記,我們隨后會在characterdata函數中使用
//
// 當遇到</story>標記時我們知道要flush所有的臨時變量準備操作下一個標記
<lt;/story>',
'title' => '</title>',
'url' => '</url>',
'author'=> '</author>'
);
?>
<?php
//下面就是定義函數來提取數據:
// 處理開始標記的屬性指
// $attrs是一個多維數組,鍵值為屬性名, 值就是該屬性的值
function startelement($parser, $name, $attrs=''){
global $open_tags, $temp, $current_tag;
$current_tag = $name;
if ($format = $open_tags[$name]){
switch($name){
case 'story':
echo '新的故事: ';
break;
default:
break;
}
}
}
// $current_tag告訴我們正在處理的標記,我們隨后會在characterdata函數中使用
//
// 當遇到</story>標記時我們知道要flush所有的臨時變量準備操作下一個標記
function endelement($parser, $name, $attrs=''){
global $close_tags, $temp, $current_tag;
if ($format = $close_tags[$name]){
switch($name){
case 'story':
return_page($temp);
$temp = '';
break;
default:
break;
}
}
}
// 傳送給此函數的是元素間的數據
// 例如,對<title>title here</title>,$data就等于'title here'
function characterdata($parser, $data){
global $current_tag, $temp, $catid;
switch($current_tag){
case 'title':
$temp['title'] = $data;
$current_tag = '';
break;
case 'url':
$temp['url'] = $data;
$current_tag = '';
break;
case 'author':
$temp['author'] = $data;
$current_tag = '';
default:
break;
}
}
?>
<?php
function return_page(){
global $temp;
echo 'o <a href="'.$temp['url'].'">'.$temp['title'].'</a><br>';
echo 'author:'.$temp['author'].'<br>';
echo '-----------------------------';
echo '<br>';
}
// 分析的內容
$xml_file = 'slashdot.xml';
// 定義字符集,默認是utf-8
$type = 'utf-8';
// 建立解析器
$xml_parser = xml_parser_create($type);
// 設置解析選項
xml_parser_set_option($xml_parser, xml_option_case_folding, true);
xml_parser_set_option($xml_parser, xml_option_target_encoding, 'utf-8');
// 告訴php發現元素時要調用什么函數
// 這些函數同時也處理元素的屬性
xml_set_element_handler($xml_parser, 'startelement','endelement');
//告訴php對字符數據調用什么函數
xml_set_character_data_handler($xml_parser, 'characterdata');
if (!($fp = fopen($xml_file, 'r'))) {
die("無法打開 $xml_file 文件進行解析!n");
}
// 通過循環來解析整個文件
while ($data = fread($fp, 4096)) {
if (!($data = utf8_encode($data))) {
echo 'error'."n";
}
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf( "xml error: %s at line %dnn",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
?>