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
40 public function getRootElement() {
41 return $this->rootElement
;
47 private function run( $fname ) {
48 $parser = xml_parser_create_ns( 'UTF-8' );
50 // case folding violates XML standard, turn it off
51 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
53 xml_set_element_handler( $parser, array( $this, 'rootElementOpen' ), false );
55 if ( file_exists( $fname ) ) {
56 $file = fopen( $fname, "rb" );
59 $chunk = fread( $file, 32768 );
60 $ret = xml_parse( $parser, $chunk, feof( $file ) );
62 // XML isn't well-formed!
64 xml_parser_free( $parser );
67 } while( !feof( $file ) );
73 $this->wellFormed
= true;
75 xml_parser_free( $parser );
83 private function rootElementOpen( $parser, $name, $attribs ) {
84 $this->rootElement
= $name;
86 if( is_callable( $this->filterCallback
) ) {
87 xml_set_element_handler( $parser, array( $this, 'elementOpen' ), false );
88 $this->elementOpen( $parser, $name, $attribs );
90 // We only need the first open element
91 xml_set_element_handler( $parser, false, false );
100 private function elementOpen( $parser, $name, $attribs ) {
101 if( call_user_func( $this->filterCallback
, $name, $attribs ) ) {
103 $this->filterMatch
= true;