Forum Moderators: open

Message Too Old, No Replies

Using PHP's SAX parser

         

Stu_Rogers

11:23 am on Aug 30, 2005 (gmt 0)

10+ Year Member



I posted this in the PHP forum about 1 week ago but have not yet relsoved it. Somebody suggested I might get a better response in this forum.

I am attempting to use PHP’s SAX parser to process an XML document, but getting the error:

Warning: xml_parse(): Unable to call handler startElementHandler() in /mnt/drbd/home/mywebsite.com/test.php
Warning: xml_parse(): Unable to call handler characterDataHandler() in /mnt/drbd/home/mywebsite.com/test.php
Warning: xml_parse(): Unable to call handler endElementHandler() in /mnt/drbd/home/mywebsite.com/test.php

These three lines are repeated for each line of my XML.

I am using PHP version 4.4.0 and when I run phpinfo I see:

XML Support active
XML Namespace Support active
EXPAT Version 1.95.6
XSLT support enabled
Backend Sablotron
Sablotron Version 1.0

Any idea why I am getting this error? Am I missing something on my server?

This is my test.php code:

$xml_parser = xml_parser_create();

//set callback functions
xml_set_element_handler($xml_parser, "startElementHandler", "endElementHandler");
xml_set_character_data_handler($xml_parser, "characterDataHandler");

//read XML file
if (!($fp = fopen("fox.xml", "r"))) {die("File error");}

//parse XML
while ($data = fread($fp, 4096)) {
//error handler
if (!xml_parse($xml_parser, $data, feof($fp))) {
die("XML Parser error: " . xml_error_string(xml_get_error_code($xml_parser)));
}
}

xml_parser_free($xml_parser);

Stu_Rogers

2:56 pm on Aug 30, 2005 (gmt 0)

10+ Year Member



Finally resolved this in the PHP forum. I had not realised that the test script was using handlers (eg,startElementHandler) which I needed to define using PHP functions. I added the code below and it is now working fine. Not a server issue after all.

//run this function when start tag is parsed
function startElementHandler ($parser, $name, $attributes) {
echo "Found opening tag of element: <b>$name</b><br>";
//process attributes
while (list ($key, $value) = each ($attributes)) {
echo "found attribute: <b>$key = $value</b><br>";
}
}

//run this function when end tag is parsed
function endElementHandler ($parser, $name) {
echo "Found closing tag of element: <b>$name</b><br>";
}

//run when cdata is parsed
function characterDataHandler ($parser, $cdata) {
echo "found CDATA: <i>$cdata</i><br>";
}

Buzbe

6:39 pm on Sep 14, 2005 (gmt 0)

10+ Year Member



I found using php's domxml is the best choice, and using pears serializer to create the xml