views:

1034

answers:

6

Unfortunatly I have to work in a older web application on a PHP4 server; It now needs to parse a lot of XML for calling webservices (custom protocol, no SOAP/REST);

Under PHP5 I would use SimpleXML but that isn't available; There is Dom XML in PHP4, but it isn't default any more in PHP5.

What are the other options? I'm looking for a solution that still works on PHP5 once they migrate.

A nice extra would be if the XML can be validated with a schema.

+3  A: 

There is a simpleXML backport avaliable: http://www.ister.org/code/simplexml44/index.html

If you can install that, then that will be the best solution.

Rich Bradshaw
A: 

Hi,

It might be a bit grass roots, but if it's applicable for the data you're working with, you could use XSLT to transform your XML in to something usable. Obviously once you upgrade to PHP5 the XSLT will still work and you can migrate as and when to DOM parsing.

Andrew

Andrew Taylor
+2  A: 

I would second Rich Bradshaw's suggestion about the simpleXML backport, but if that's not an option, then xml_parse will do the job in PHP4, and still works after migration to 5.

$xml = ...; // Get your XML data
$xml_parser = xml_parser_create();

// _start_element and _end_element are two functions that determine what
// to do when opening and closing tags are found
xml_set_element_handler($xml_parser, "_start_element", "_end_element");

// How to handle each char (stripping whitespace if needs be, etc
xml_set_character_data_handler($xml_parser, "_character_data");  

xml_parse($xml_parser, $xml);

There's a good tutorial here about parsing XML in PHP4 that may be of some use to you.

ConroyP
A: 

If you can use xml_parse, then go for that. It's robust, fast and compatible with PHP5. It is however not a DOM parser, but a simpler event-based one (Also called a SAX parser), so if you need to access a tree, you will have to marshal the stream into a tree your self. This is fairly simple to do; Use s stack, and push items to it on start-element and pop on end-element.

troelskn
A: 

I would definitely recommend the SimpleXML backport, as long as its performance is good enough for your needs. The demonstrations of xml_parse look simple enough, but it can get very hairy very quickly in my experience. The content handler functions don't get any contextual information about where the parser is in the tree, unless you track it and provide it in the start and end tag handlers. So you're either calling functions for every start/end tag, or throwing around global variables to track where you are in the tree.

Obviously the SimpleXML backport will be a bit slower, as it's written in PHP and has to parse the whole document before it's available, but the ease of coding more than makes up for it.

dkuchler
A: 

Maybe also consider looking at the XML packages available in PEAR, particularly *XML_Util*, *XML_Parser*, and *XML_Serializer*...

ashnazg