5 * Will be set to true or false to indicate whether the file is
6 * well-formed XML. Note that this doesn't check schema validity.
8 public $wellFormed = false;
11 * Will be set to true if the optional element filter returned
12 * a match at some point.
14 public $filterMatch = false;
17 * Name of the document's root element, including any namespace
20 public $rootElement = '';
23 * @param $file string filename
24 * @param $filterCallback callable (optional)
25 * Function to call to do additional custom validity checks from the
26 * SAX element handler event. This gives you access to the element
27 * namespace, name, and attributes, but not to text contents.
28 * Filter should return 'true' to toggle on $this->filterMatch
30 function __construct( $file, $filterCallback=null ) {
31 $this->filterCallback
= $filterCallback;
36 * Get the root element. Simple accessor to $rootElement
38 public function getRootElement() {
39 return $this->rootElement
;
42 private function run( $fname ) {
43 $parser = xml_parser_create_ns( 'UTF-8' );
45 // case folding violates XML standard, turn it off
46 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
48 xml_set_element_handler( $parser, array( $this, 'rootElementOpen' ), false );
50 $file = fopen( $fname, "rb" );
52 $chunk = fread( $file, 32768 );
53 $ret = xml_parse( $parser, $chunk, feof( $file ) );
55 // XML isn't well-formed!
57 xml_parser_free( $parser );
60 } while( !feof( $file ) );
62 $this->wellFormed
= true;
65 xml_parser_free( $parser );
68 private function rootElementOpen( $parser, $name, $attribs ) {
69 $this->rootElement
= $name;
71 if( is_callable( $this->filterCallback
) ) {
72 xml_set_element_handler( $parser, array( $this, 'elementOpen' ), false );
73 $this->elementOpen( $parser, $name, $attribs );
75 // We only need the first open element
76 xml_set_element_handler( $parser, false, false );
80 private function elementOpen( $parser, $name, $attribs ) {
81 if( call_user_func( $this->filterCallback
, $name, $attribs ) ) {
83 $this->filterMatch
= true;