Home > PHP, Web Development > Handling CType Data With SimpleXML in PHP

Handling CType Data With SimpleXML in PHP

January 16th, 2010 Chris Leave a comment Go to comments

If you're new to SimpleXML then the output and representation of complex XML data produced by the library can be daunting and sometimes confusing, but once you're used to it, SimpleXML is a massively useful tool for processing XML information.

When debugging other people's implementations of simpleXML however, one of the biggest issues I come across time and again is the apparent loss of CType data from the processed feed.

Luckily this is very easily remedied, but not well documented so here's how to deal with it.

PHP 5.1.0 introduced the options parameter to functions such as simplexml_load_string() which allows you to specify additional paramters to Libxml the underlying library PHP uses to interpret XML.

The default Libxml setting ignores any data in CType blocks, but you can override this behaviour by passing the LIBXML_NOCDATA option to the function.

In other words, in cases where you might usually do this to load some xml data and not find the CType fields in the resulting object:

$xml = simplexml_load_string($feed);

Doing this instead, will allow the CType fields to be added to the object and used in your scripts where you need to

$xml = simplexml_load_string($feed, NULL, LIBXML_NOCDATA);

Unfortunately the options parameter is the 3rd in the list, and 9 times out of 10 the second option (which is the name that's given to the class containing the parsed xml) doesn't need to be changed/overridden so I personally choose to pass NULL in as the second option, though you can enter whatever you like here.

It's as easy as that  - I hope you found this note useful :)

Related posts on coderchris.com:

  1. Searching for words that "sounds like…"
    This article is interesting: http://lamp.codeproject.com/KB/recipes/soundslike.aspx Combining methods to better search for words that sound like...
  2. Bloody MySQL Bugs
    I’m looking to setup some replication between two servers and server B has none of...
  3. Funky ORM with PHPDoctrine
    I work on all sorts of little personal projects in my spare time, most of...
  4. Getting Wordpress To Ping Google Blog Search
    I noticed today that my blog wasn't included in Google blog search, so I set...
  5. Styling the The TinyMCE Text Area
    They guys who produce TinyMCE suggest, when initialising the editor, that you set the content_css...

  1. No comments yet.
  1. No trackbacks yet.