PHP XML解析器函数

PHP xml_get_error_code() 函数返回 XML 解析器错误代码。如果parser没有引用有效的解析器,该函数返回 false,否则返回错误代码。

语法

xml_get_error_code(parser) 

参数

parser必需。 指定对 XML 解析器的引用以从中获取错误代码。

返回值

如果 parser 没有引用有效的解析器,否则它会返回错误代码。

示例:错误(字符串未用双引号括起来)

让我们假设我们有一个名为 demo.xml 的文件。该文件包含以下内容。内容包含错误(用双引号括起来的字符串)。

<?xml version="1.0 encoding="UTF-8"?>
<userlist>
  <user>
    <username>John123</username>
    <name>John Smith</name>
    <phone>+1-8054098000</phone>
    <address>Brooklyn, New York, USA</address>
  </user>
</userlist> 

在下面的示例中,解析了 XML 文件。它在解析文档时显示错误。

<?php
//创建XML解析器
$parser=xml_parser_create();

//打开xml文件
$fp = fopen("demo.xml", "r");

while($data = fread($fp,4096)) {
  //解析XML数据
  if(!xml_parse($parser, $data, feof($fp))) {
    //显示错误
    die(print "Error: " .
      //错误字符串
      xml_error_string(xml_get_error_code($parser)) .
       
      "<br/>Error Code: " . 
      //错误代码
      xml_get_error_code($parser) .
       
      "<br/>Line: " .
      //发生错误的行号
      xml_get_current_line_number($parser) .
       
      "<br/>Column: " .
      //发生错误的列号
      xml_get_current_column_number($parser) .
       
      "<br/>Byte Index: " .
      //发生错误的字节索引
      xml_get_current_byte_index($parser) . "<br/>"
    );
  }
}

//免费的XML解析器
xml_get_error_coder_free($parser);

fclose($fp);
?> 

上述代码的输出将是:

Error: String not closed expecting " or '
Error Code: 34
Line: 1
Column: 38
Byte Index: 37 

示例:错误(标签不匹配)

假设我们有一个文件称为example.xml。该文件包含以下内容。内容包含错误(标签不匹配)。

<?xml version="1.0" encoding="UTF-8"?>
<userlist>
  <user>
    <username>John123</username>
    <name>John Smith</name>
    <phone>+1-8054098000</phone>
    <address>Brooklyn, New York, USA<address>
  </user>
</userlist> 

在下面的示例中,解析了 XML 文件。它在解析文档时显示错误。

<?php
//创建XML解析器
$parser=xml_parser_create();

//打开xml文件
$fp = fopen("example.xml", "r");

while($data = fread($fp,4096)) {
  //解析XML数据
  if(!xml_parse($parser, $data, feof($fp))) {
    //显示错误
    die(print "Error: " .
      //错误字符串
      xml_error_string(xml_get_error_code($parser)) .
       
      "<br/>Error Code: " . 
      //错误代码
      xml_get_error_code($parser) .
       
      "<br/>Line: " .
      //发生错误的行号
      xml_get_current_line_number($parser) .
       
      "<br/>Column: " .
      //发生错误的列号
      xml_get_current_column_number($parser) .
       
      "<br/>Byte Index: " .
      //发生错误的字节索引
      xml_get_current_byte_index($parser) . "<br/>"
    );
  }
}

//免费的XML解析器
xml_get_error_coder_free($parser);

fclose($fp);
?> 

上述代码的输出将是:

Error: Mismatched tag
Error Code: 76
Line: 8
Column: 10
Byte Index: 220