Monday, July 20, 2009

My favorite PHP Class: SimpleXMLElement

1. A lot effort has been expended by countless people to convert XML into PHP arrays. There are countless forum discussions on the subject and many complex scripts to accomplish this task.

But there is something better.

$xml = simplexml_load_string($str);

One line of code converts an XML string to an object of class SimpleXMLElement. Then you can access any individual data element within the object simply by calling the surrounding tags (skipping the outermost [message] tags):

$xml->body->layer1->layer2->layer3

2. It is very useful for debugging objects to have a way of examining the object structure, datatypes, and content. The very useful function for this is var_dump($obj); which lays everything out for you (kind of like print_r($arr); for arrays).

3. Another strange discovery I have made is that instead of enclosing lenghty XML strings in quotes or double quotes, it is possible to dispense with the quotes altogether and enclose it with XML preceded by three "less-than" signs on one end and XML on the other end. I am not sure why this is so or what the ramifications are of this, but it looks like a very useful option.

No comments:

Post a Comment