generate XML from Object... AND... XML from Array... AND XML from Array


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1.  
  2. class XMLSerializer {
  3.  
  4. // functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/
  5.  
  6. public static function generateValidXmlFromObj($obj, $node_block='nodes', $node_name='node') {
  7. $arr = get_object_vars($obj);
  8. return self::generateValidXmlFromArray($arr, $node_block, $node_name);
  9. }
  10.  
  11. public static function generateValidXmlFromArray($array, $node_block='nodes', $node_name='node') {
  12. $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
  13.  
  14. $xml .= '<' . $node_block . '>';
  15. $xml .= self::generateXmlFromArray($array, $node_name);
  16. $xml .= '</' . $node_block . '>';
  17.  
  18. return $xml;
  19. }
  20.  
  21. private static function generateXmlFromArray($array, $node_name) {
  22. $xml = '';
  23.  
  24. if (is_array($array) || is_object($array)) {
  25. foreach ($array as $key=>$value) {
  26. if (is_numeric($key)) {
  27. $key = $node_name;
  28. }
  29.  
  30. $xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
  31. }
  32. } else {
  33. $xml = htmlspecialchars($array, ENT_QUOTES);
  34. }
  35.  
  36. return $xml;
  37. }
  38.  
  39. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.