Advertisement
halleman19

php array to xml (multi/single levels)

Jan 3rd, 2025
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.69 KB | None | 0 0
  1. <?php
  2.  
  3.     // multi/signel converter array to xml
  4.     // example: https://imgur.com/a/LsQY8A7
  5.  
  6.     function printResponse($data)
  7.     {
  8.         $xml = new DOMDocument();
  9.        
  10.         $root = $xml->appendChild($xml->createElement('root'));
  11.         $response = $root->appendChild($xml->createElement('response'));
  12.        
  13.         arrayToXml($xml, $response, $data);
  14.        
  15.         header("Content-Type: text/plain");
  16.         $xml->formatOutput = true;
  17.        
  18.         die($xml->saveXml());
  19.     }
  20.    
  21.     function arrayToXml($xml, $root, $data)
  22.     {
  23.         foreach($data as $key => $item)
  24.         {
  25.             if(is_array($item))
  26.                 arrayToXml($xml, $root->appendChild($xml->createElement($key)), $item);
  27.             else
  28.                 $root->appendChild($xml->createElement($key, $item));
  29.         }
  30.     }
  31.  
  32. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement