Tuesday, December 16, 2008

Gotcha Of The Day - Submitting Raw XML To PHP

This shouldn't have been tricky - but it stumped me for just long enough to declare it a Gotcha Of The Day.

I'm working on a Flex app, and wanted to POST some basic XML to a PHP script so that it could slurp in the data. Nothing too exotic there. By default PHP hides the whole complexity of reading in a POST, and just provides you with $_POST. However, in this case, I didn't want to use URL encoded values.

After poking around, I found this useful example. It makes use of the magic file php://input.

So, suppose I POST'ed the following XML from Flex:

  <lunch>
   <main>Chicken leftovers</main>
   <side>soy chips</side>
   <desert>Tofuti</desert>
   <drink>H2O</drink>
  </lunch>

(See where my head's currently at?)

I can use the following code:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $meal= new SimpleXMLElement(file_get_contents('php://input'));
}

This not only reads in the post manually, but also creates a SimpleXML object. Which means I can then do:

  record_meal($meal->main, $meal->side, $meal->drink, $meal->desert);

I'm really loving how SimpleXML parses the objects that Flex creates using it's SimpleXMLEncoder. This means that while the transport mechanism is XML, I can keep thinking in terms of objects.

No comments:

Post a Comment