xref: /PHP-8.2/ext/xml/tests/xml001.phpt (revision 8567bc10)
1--TEST--
2XML parser test, function callbacks
3--EXTENSIONS--
4xml
5--SKIPIF--
6<?php
7XML_SAX_IMPL == 'libxml' && die('skip this test is not intended for libxml SAX parser');
8?>
9--FILE--
10<?php
11chdir(__DIR__);
12
13$xml_parser = xml_parser_create();
14xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
15xml_set_element_handler($xml_parser, "startElement", "endElement");
16xml_set_character_data_handler($xml_parser, "characterData");
17xml_set_processing_instruction_handler($xml_parser, "PIHandler");
18xml_set_default_handler($xml_parser, "defaultHandler");
19xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");
20
21if (!($fp = @fopen("xmltest.xml", "r"))) {
22    die("could not open XML input");
23}
24
25while ($data = fread($fp, 4096)) {
26    if (!xml_parse($xml_parser, $data, feof($fp))) {
27        die(sprintf("XML error: %s at line %d\n",
28        xml_error_string(xml_get_error_code($xml_parser)),
29        xml_get_current_line_number($xml_parser)));
30    }
31}
32print "parse complete\n";
33xml_parser_free($xml_parser);
34
35function startElement($parser, $name, $attribs)
36{
37    print '{'.$name;
38    if (sizeof($attribs)) {
39        foreach ($attribs as $k => $v) {
40            print " $k=\"$v\"";
41        }
42    }
43    print '}';
44}
45
46function endElement($parser, $name)
47{
48    print '{/'.$name.'}';
49}
50
51function characterData($parser, $data)
52{
53    print '{CDATA['.$data.']}';
54}
55
56function PIHandler($parser, $target, $data)
57{
58    print '{PI['.$target.','.$data.']}';
59}
60
61function defaultHandler($parser, $data)
62{
63    if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
64        print '{ENTREF['.$data.']}';
65    } else {
66        print '{?['.$data.']}';
67    }
68}
69
70function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId, $publicId)
71{
72    print '{EXTENTREF['.$openEntityNames.','.$base.','.$systemId.','.$publicId."]}\n";
73    return true;
74}
75
76?>
77--EXPECT--
78{?[<?xml version="1.0" encoding="ISO-8859-1"?>]}{?[
79]}{?[<!DOCTYPE]}{?[ ]}{?[phptest]}{?[ ]}{?[SYSTEM]}{?[ ]}{?["notfound.dtd"]}{?[ ]}{?[[]}{?[
80]}{?[<!ENTITY]}{?[ ]}{?[%]}{?[ ]}{?[incent]}{?[ ]}{?[SYSTEM]}{?[ ]}{?["inc.ent"]}{?[>]}{?[
81]}{?[%incent;]}{?[
82]}{?[]]}{?[>]}{?[
83]}{ROOT ID="elem1"}{CDATA[
84]}{CDATA[ Plain text.]}{CDATA[
85]}{CDATA[ ]}{ELEM1}{CDATA[
86]}{CDATA[  ]}{?[<!-- comment -->]}{CDATA[
87]}{CDATA[  ]}{ELEM2}{CDATA[
88]}{CDATA[   ]}{?[<![CDATA[]}{CDATA[CDATA block]}{?[]]>]}{CDATA[
89]}{CDATA[   ]}{ELEM3}{CDATA[
90]}{CDATA[    ]}{ENTREF[&included-entity;]}{CDATA[
91]}{CDATA[    ]}{ELEM4}{CDATA[
92]}{CDATA[     ]}{PI[test,processing instruction ]}{CDATA[
93]}{CDATA[    ]}{/ELEM4}{CDATA[
94]}{CDATA[   ]}{/ELEM3}{CDATA[
95]}{CDATA[  ]}{/ELEM2}{CDATA[
96]}{CDATA[ ]}{/ELEM1}{CDATA[
97]}{/ROOT}{?[
98]}parse complete
99