PHP Manual
Prev |  | Next

# LVI. XML parser functions

# Introduction

## About XML

XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at http://www.w3.org/XML/.

## Installation

This extension uses expat, which can be found at http://www.jclark.com/xml/. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:

      1
      2 libexpat.a: $(OBJS)
      3 	ar -rc $@ $(OBJS)
      4 	ranlib $@
      5

A source RPM package of expat can be found at http://www.guardian.no/~ssb/phpxml.html.

Note that if you are using Apache-1.3.7 or later, you already have the required expat library. Simply configure PHP using `--with-xml` (without any additional path) and it will automatically use the expat library built into Apache.

On UNIX, run configure with the `--with-xml` option. The expat library should be installed somewhere your compiler can find it. If you compile PHP as a module for Apache 1.3.9 or later, PHP will automatically use the bundled expat library from Apache. You may need to set `CPPFLAGS` and `LDFLAGS` in your environment before running configure if you have installed expat somewhere exotic.

Build PHP. Tada! That should be it.

## About This Extension

This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: `US-ASCII`, `ISO-8859-1` and `UTF-8`. `UTF-16` is not supported.

This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.

The XML event handlers defined are:

Table 1. Supported XML handlers

PHP function to set handler | Event description
--- | ---
xml_set_element_handler() | Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags.
xml_set_character_data_handler() | Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant.
xml_set_processing_instruction_handler() | PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where `php` is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved.
xml_set_default_handler() | What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler.
xml_set_unparsed_entity_decl_handler() | This handler will be called for declaration of an unparsed (NDATA) entity.
xml_set_notation_decl_handler() | This handler is called for declaration of a notation.
xml_set_external_entity_ref_handler() | This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration.

## Case Folding

The element handler functions may get their element names case-folded. Case-folding is defined by the XML standard as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.

By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.

## Error Codes

The following constants are defined for XML error codes (as returned by xml_parse()):

XML_ERROR_NONE
XML_ERROR_NO_MEMORY
XML_ERROR_SYNTAX
XML_ERROR_NO_ELEMENTS
XML_ERROR_INVALID_TOKEN
XML_ERROR_UNCLOSED_TOKEN
XML_ERROR_PARTIAL_CHAR
XML_ERROR_TAG_MISMATCH
XML_ERROR_DUPLICATE_ATTRIBUTE
XML_ERROR_JUNK_AFTER_DOC_ELEMENT
XML_ERROR_PARAM_ENTITY_REF
XML_ERROR_UNDEFINED_ENTITY
XML_ERROR_RECURSIVE_ENTITY_REF
XML_ERROR_ASYNC_ENTITY
XML_ERROR_BAD_CHAR_REF
XML_ERROR_BINARY_ENTITY_REF
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
XML_ERROR_MISPLACED_XML_PI
XML_ERROR_UNKNOWN_ENCODING
XML_ERROR_INCORRECT_ENCODING
XML_ERROR_UNCLOSED_CDATA_SECTION
XML_ERROR_EXTERNAL_ENTITY_HANDLING

## Character Encoding

PHP's XML extension supports the Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with `UTF-8`.

Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are `ISO-8859-1`, `US-ASCII` and `UTF-8`. The former two are single-byte encodings, which means that each character is represented by a single byte. `UTF-8` can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is `ISO-8859-1`.

Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.

If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.

If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.

# Some Examples

Here are some example PHP scripts parsing XML documents.

## XML Element Structure Example

This first example displays the stucture of the start elements in a document with indentation.

Example 1. Show XML Element Structure
      1
      2 $file = "data.xml";
      3 $depth = array();
      4
      5 function startElement($parser, $name, $attrs) {
      6     global $depth;
      7     for ($i = 0; $i < $depth[$parser]; $i++) {
      8         print "  ";
      9     }
     10     print "$name\n";
     11     $depth[$parser]++;
     12 }
     13
     14 function endElement($parser, $name) {
     15     global $depth;
     16     $depth[$parser]--;
     17 }
     18
     19 $xml_parser = xml_parser_create();
     20 xml_set_element_handler($xml_parser, "startElement", "endElement");
     21 if (!($fp = fopen($file, "r"))) {
     22     die("could not open XML input");
     23 }
     24
     25 while ($data = fread($fp, 4096)) {
     26     if (!xml_parse($xml_parser, $data, feof($fp))) {
     27         die(sprintf("XML error: %s at line %d",
     28                     xml_error_string(xml_get_error_code($xml_parser)),
     29                     xml_get_current_line_number($xml_parser)));
     30     }
     31 }
     32 xml_parser_free($xml_parser);
     33

## XML Tag Mapping Example

Example 2. Map XML to HTML This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.
      1
      2 $file = "data.xml";
      3 $map_array = array(
      4     "BOLD"     => "B",
      5     "EMPHASIS" => "I",
      6     "LITERAL"  => "TT"
      7 );
      8
      9 function startElement($parser, $name, $attrs) {
     10     global $map_array;
     11     if ($htmltag = $map_array[$name]) {
     12         print "<$htmltag>";
     13     }
     14 }
     15
     16 function endElement($parser, $name) {
     17     global $map_array;
     18     if ($htmltag = $map_array[$name]) {
     19         print "</$htmltag>";
     20     }
     21 }
     22
     23 function characterData($parser, $data) {
     24     print $data;
     25 }
     26
     27 $xml_parser = xml_parser_create();
     28 // use case-folding so we are sure to find the tag in $map_array
     29 xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
     30 xml_set_element_handler($xml_parser, "startElement", "endElement");
     31 xml_set_character_data_handler($xml_parser, "characterData");
     32 if (!($fp = fopen($file, "r"))) {
     33     die("could not open XML input");
     34 }
     35
     36 while ($data = fread($fp, 4096)) {
     37     if (!xml_parse($xml_parser, $data, feof($fp))) {
     38         die(sprintf("XML error: %s at line %d",
     39                     xml_error_string(xml_get_error_code($xml_parser)),
     40                     xml_get_current_line_number($xml_parser)));
     41     }
     42 }
     43 xml_parser_free($xml_parser);
     44

## XML External Entity Example

This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.

XML documents that can be used for this example are found below the example (`xmltest.xml` and `xmltest2.xml`.)

Example 3. External Entity Example
      1
      2 $file = "xmltest.xml";
      3
      4 function trustedFile($file) {
      5     // only trust local files owned by ourselves
      6     if (!eregi("^([a-z]+)://", $file)
      7         && fileowner($file) == getmyuid()) {
      8             return true;
      9     }
     10     return false;
     11 }
     12
     13 function startElement($parser, $name, $attribs) {
     14     print "&lt;<font color=\"#0000cc\">$name</font>";
     15     if (sizeof($attribs)) {
     16         while (list($k, $v) = each($attribs)) {
     17             print " <font color=\"#009900\">$k</font>=\"<font
     18                    color=\"#990000\">$v</font>\"";
     19         }
     20     }
     21     print "&gt;";
     22 }
     23
     24 function endElement($parser, $name) {
     25     print "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
     26 }
     27
     28 function characterData($parser, $data) {
     29     print "<b>$data</b>";
     30 }
     31
     32 function PIHandler($parser, $target, $data) {
     33     switch (strtolower($target)) {
     34         case "php":
     35             global $parser_file;
     36             // If the parsed document is "trusted", we say it is safe
     37             // to execute PHP code inside it.  If not, display the code
     38             // instead.
     39             if (trustedFile($parser_file[$parser])) {
     40                 eval($data);
     41             } else {
     42                 printf("Untrusted PHP code: <i>%s</i>",
     43                         htmlspecialchars($data));
     44             }
     45             break;
     46     }
     47 }
     48
     49 function defaultHandler($parser, $data) {
     50     if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
     51         printf('<font color="#aa00aa">%s</font>',
     52                 htmlspecialchars($data));
     53     } else {
     54         printf('<font size="-1">%s</font>',
     55                 htmlspecialchars($data));
     56     }
     57 }
     58
     59 function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
     60                                   $publicId) {
     61     if ($systemId) {
     62         if (!list($parser, $fp) = new_xml_parser($systemId)) {
     63             printf("Could not open entity %s at %s\n", $openEntityNames,
     64                    $systemId);
     65             return false;
     66         }
     67         while ($data = fread($fp, 4096)) {
     68             if (!xml_parse($parser, $data, feof($fp))) {
     69                 printf("XML error: %s at line %d while parsing entity %s\n",
     70                        xml_error_string(xml_get_error_code($parser)),
     71                        xml_get_current_line_number($parser), $openEntityNames);
     72                 xml_parser_free($parser);
     73                 return false;
     74             }
     75         }
     76         xml_parser_free($parser);
     77         return true;
     78     }
     79     return false;
     80 }
     81
     82
     83 function new_xml_parser($file) {
     84     global $parser_file;
     85
     86     $xml_parser = xml_parser_create();
     87     xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
     88     xml_set_element_handler($xml_parser, "startElement", "endElement");
     89     xml_set_character_data_handler($xml_parser, "characterData");
     90     xml_set_processing_instruction_handler($xml_parser, "PIHandler");
     91     xml_set_default_handler($xml_parser, "defaultHandler");
     92     xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");
     93
     94     if (!($fp = @fopen($file, "r"))) {
     95         return false;
     96     }
     97     if (!is_array($parser_file)) {
     98         settype($parser_file, "array");
     99     }
    100     $parser_file[$xml_parser] = $file;
    101     return array($xml_parser, $fp);
    102 }
    103
    104 if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
    105     die("could not open XML input");
    106 }
    107
    108 print "<pre>";
    109 while ($data = fread($fp, 4096)) {
    110     if (!xml_parse($xml_parser, $data, feof($fp))) {
    111         die(sprintf("XML error: %s at line %d\n",
    112                     xml_error_string(xml_get_error_code($xml_parser)),
    113                     xml_get_current_line_number($xml_parser)));
    114     }
    115 }
    116 print "</pre>";
    117 print "parse complete\n";
    118 xml_parser_free($xml_parser);
    119
    120 ?>
    121

Example 4. xmltest.xml
      1
      2 <?xml version='1.0'?>
      3 <!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
      4 <!ENTITY plainEntity "FOO entity">
      5 <!ENTITY systemEntity SYSTEM "xmltest2.xml">
      6 ]>
      7 <chapter>
      8  <TITLE>Title &plainEntity;</TITLE>
      9  <para>
     10   <informaltable>
     11    <tgroup cols="3">
     12     <tbody>
     13      <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
     14      <row><entry>a2</entry><entry>c2</entry></row>
     15      <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
     16     </tbody>
     17    </tgroup>
     18   </informaltable>
     19  </para>
     20  &systemEntity;
     21  <sect1 id="about">
     22   <title>About this Document</title>
     23   <para>
     24    <!-- this is a comment -->
     25    <?php print 'Hi!  This is PHP version '.phpversion(); ?>
     26   </para>
     27  </sect1>
     28 </chapter>
     29

This file is included from `xmltest.xml`:

Example 5. xmltest2.xml
      1
      2 <?xml version="1.0"?>
      3 <!DOCTYPE foo [
      4 <!ENTITY testEnt "test entity">
      5 ]>
      6 <foo>
      7    <element attrib="value"/>
      8    &testEnt;
      9    <?php print "This is some more PHP code being executed."; ?>
     10 </foo>
     11

Prev | Home | Next
wddx_deserialize | Up | xml_parser_create