3 * XML syntax and type checker.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Will be set to true or false to indicate whether the file is
26 * well-formed XML. Note that this doesn't check schema validity.
28 public $wellFormed = false;
31 * Will be set to true if the optional element filter returned
32 * a match at some point.
34 public $filterMatch = false;
37 * Name of the document's root element, including any namespace
40 public $rootElement = '';
43 * @param $file string filename
44 * @param $filterCallback callable (optional)
45 * Function to call to do additional custom validity checks from the
46 * SAX element handler event. This gives you access to the element
47 * namespace, name, and attributes, but not to text contents.
48 * Filter should return 'true' to toggle on $this->filterMatch
50 function __construct( $file, $filterCallback=null ) {
51 $this->filterCallback
= $filterCallback;
56 * Get the root element. Simple accessor to $rootElement
60 public function getRootElement() {
61 return $this->rootElement
;
67 private function run( $fname ) {
68 $parser = xml_parser_create_ns( 'UTF-8' );
70 // case folding violates XML standard, turn it off
71 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
73 xml_set_element_handler( $parser, array( $this, 'rootElementOpen' ), false );
75 if ( file_exists( $fname ) ) {
76 $file = fopen( $fname, "rb" );
79 $chunk = fread( $file, 32768 );
80 $ret = xml_parse( $parser, $chunk, feof( $file ) );
82 // XML isn't well-formed!
84 xml_parser_free( $parser );
87 } while( !feof( $file ) );
93 $this->wellFormed
= true;
95 xml_parser_free( $parser );
103 private function rootElementOpen( $parser, $name, $attribs ) {
104 $this->rootElement
= $name;
106 if( is_callable( $this->filterCallback
) ) {
107 xml_set_element_handler( $parser, array( $this, 'elementOpen' ), false );
108 $this->elementOpen( $parser, $name, $attribs );
110 // We only need the first open element
111 xml_set_element_handler( $parser, false, false );
120 private function elementOpen( $parser, $name, $attribs ) {
121 if( call_user_func( $this->filterCallback
, $name, $attribs ) ) {
123 $this->filterMatch
= true;