Christopher Bergin Posted March 28, 2013 Share Posted March 28, 2013 I'm trying to understand the flow of execution in the parser script (expat.php script 13.8) Does the parse function xml_parse($p, $data, feof($fp)) automatically call the element_handler function xml_set_element_handler($p, 'handle_open_element', 'handle_close_element') and if so, do the arguments in the parse function correspond to the parameters of the handler function? Is the handler function a recursive routine because I don't understand how the open and close functions can simultaneously be invoked. // Function for handling the open tag: function handle_open_element($p, $element, $attributes) { // Do different things based upon the element: switch ($element) { // Need to address: book, title, author, year, chapter, and pages! case 'BOOK': // Books are DIV's: echo '<div>'; break; // Function for handling the closing tag: function handle_close_element($p, $element) { // Do different things based upon the element: switch ($element) { // Close up HTML tags... case 'BOOK': // Books are DIV's: echo '</div>'; break; // Create the parser: $p = xml_parser_create(); // Set the handling functions: xml_set_element_handler($p, 'handle_open_element', 'handle_close_element'); xml_set_character_data_handler($p, 'handle_character_data'); // Read the file: $file = 'books2.xml'; $fp = @fopen($file, 'r') or die("<p>Could not open a file called '$file'.</p></body></html>"); while ($data = fread($fp, 4096)) { xml_parse($p, $data, feof($fp)); } // Free up the parser: xml_parser_free($p); ?> </body> </html> Link to comment Share on other sites More sharing options...
Larry Posted March 30, 2013 Share Posted March 30, 2013 The xml_set_element_handler() function is NOT called by the parsing function. xml_set_element_handler() is called once automatically in the flow of the script. What it does is tell the parser what functions to call when opening and closing tags are encountered. Those functions are not invoked simultaneously. Think of it this way: I'm giving you driving instructions. At the start, I say that when the light turns green, you press the gas and when the light turns red, you press the brake. That's what the xml_set_element_handler() function is doing. Then you start driving (parsing). And the light turns green, so you know to press the gas (i.e., the parser encounters an opening tag, so it invokes the one function). Later, the light (different light) turns red, so you know to press the brake. Does that make sense? Link to comment Share on other sites More sharing options...
Christopher Bergin Posted March 30, 2013 Author Share Posted March 30, 2013 yes, the process seems to be a lot simpler than the one I was envisioning. Thanks for clearing that up. Link to comment Share on other sites More sharing options...
Recommended Posts