CodersAdvocate

I work hard, so you don't have to

Parse Object To XML with PHP

 

Parsing data to XML with PHP has never been easier now that PHP 5 has a reflector.

I am going to start off this little php helper by talking about Microsoft.
Alot of people give them alot of stick, and somtimes deservadly so. But there is one thing, and ONLY one thing that microsoft does very well, and thats write programming languages.

ASP.NET has the simplest object to XML serialisation, but not anymore.

Now that php supports reflection it is as simple as getting the function right to serialise.
Then you simply change the headers to xml and print this XML out, and you have the basis for a webservice infrastructure.

Heres the code...

GeSHi © 2004-2007 Nigel McNie, 2007-2009 Benny Baumann, 2008-2009 Milian Wolff
  1. echo "\"1.0\"?>";
  2. header("Content-type: application/xml");
  3. serialise($Object_Goes_Here);
  4. function serialise($objectIn) {
  5. $reflectedObject = new ReflectionClass($objectIn);
  6. $myObjName = strtolower($reflectedObject->name);
  7. echo "<$myObjName>";
  8. foreach (array_values($reflectedObject->getProperties()) as $method) {
  9. $name = array();
  10. $name[0] = $method->name;
  11. $value = $objectIn->$name[0];
  12. $valueType = gettype($value);
  13. $name[1] = strtolower($name[0]);
  14. if ($valueType == "array")
  15. {
  16. echo "<$name[1] type=\"$valueType\" size=\"" . sizeof($objectIn->$name[0]) . "\">";
  17. foreach($objectIn->$name[0] as $item){
  18. //if item can change to a string do this
  19. $itemType = gettype($item);
  20. if ($itemType == "string"){
  21. echo "<$name[1] type=\"$itemType\">";
  22. echo $item;
  23. echo "$name[1]>";
  24. }else{
  25. toDataObj($item);
  26. }
  27. }
  28. echo "$name[1]>";
  29. }
  30. else
  31. {
  32. echo "<$name[1] type=\"$valueType\">";
  33. echo $value;
  34. echo "$name[1]>";
  35. }
  36. }
  37. echo "$myObjName>";
  38. }
  39. ?>
Parsed in 0.953 seconds at 1.14 KB/s
Copyright 2011 CodersAdvocate ©