PHP xml_parse() 函数

PHP 教程 · 2019-01-30 18:12:12

定义和用法

xml_parse() 函数解析 XML 文档。

如果成功,该函数则返回 TRUE。如果失败,则返回 FALSE。

语法


xml_parse(parser,xml,end)


参数 描述
parser 必需。规定要使用的 XML 解析器。
xml 必需。规定要解析的 XML 数据。
end 可选。如果该参数是 TRUE,则 "xml" 参数中的数据为当前解析中最后一段数据。

注释: 实体错误在解析的最后被报告,且仅在 "end" 参数是 TRUE 时才显示。


提示和注释

提示:要创建 XML 解析器,请使用 xml_parser_create() 函数。

实例 1

XML 文件


<?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
$parser=xml_parser_create();
function char($parser,$data)
  {
  echo $data;
  }
xml_set_character_data_handler($parser,"char");
$fp=fopen("test.xml","r");
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)));
  }
xml_parser_free($parser);
?>

上面代码的输出如下所示:


Tove Jani Reminder Don't forget me this weekend!


实例 2

使用相同的 XML 文件但通过不同的方式显示 XML 数据:


<?php
$parser=xml_parser_create();
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 stop($parser,$element_name)
  {
  echo "<br />";
  }
function char($parser,$data)
  {
  echo $data;
  }
xml_set_element_handler($parser,"start","stop");
xml_set_character_data_handler($parser,"char");
$fp=fopen("test.xml","r");
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)));
  }
xml_parser_free($parser);
?>

上面代码的输出如下所示:


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


点击查看所有 PHP 教程 文章: https://codercto.com/courses/l/5.html

查看所有标签

Pattern Recognition and Machine Learning

Pattern Recognition and Machine Learning

Christopher Bishop / Springer / 2007-10-1 / USD 94.95

The dramatic growth in practical applications for machine learning over the last ten years has been accompanied by many important developments in the underlying algorithms and techniques. For example,......一起来看看 《Pattern Recognition and Machine Learning》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试