-2

I have an array like

$a = array(
    'aaa' => "sample",
    'bbb' => "sample2",
    'ccc' => "adas",
    'ddd' => "2",
    'eee' => '2013-09-05',
    'fff' => "false",
    'ggg' => "893",
    'qqq' => '2013-09-05',
    'sss' => array(
        "iii" => array(
            'vvv' => "sample3",
            'xxx' => 500,
        )
    ),
    'nnn' => '2013-09-05',
    'mmm' => "Normal",
);

and I want to convert it to xml but witout using SimpleXMLElement or another function. That's why I have tried to do it with foreach. Here is my code ;

$data = '';
foreach ($a as $k => $v) {

    if (is_array($k)) {
        $data .= "<a:$k>" . $v . "</a:$k>";
        foreach ($k as $j => $m) {
            if (is_array($j)) {
                foreach ($j as $s => $p) {
                    $data .= "<a:$s>" . $p . "</a:$s>";
                }
            } else {
                $data .= "<a:$j>" . $m . "</a:$j>";
            }
        }
    } else {
        $data .= "<a:$k>" . $v . "</a:$k>";
    }
}

but it's not working. I can make it work with hashmaps in another language but it must be in php. How can I do this.

Thanks.

Nigel B
  • 3,577
  • 3
  • 34
  • 52
omrcm
  • 31
  • 3
  • 9
  • You should use recursion – Joren Sep 11 '13 at 11:08
  • possible duplicate of [How to convert array to SimpleXML](http://stackoverflow.com/questions/1397036/how-to-convert-array-to-simplexml) – Bora Sep 11 '13 at 11:10
  • @BORA S.A. I know but I'll not use this function. Because I have another controls before it's convert – omrcm Sep 11 '13 at 11:26

1 Answers1

2

You could try this:

function createXml($array, $level = 0)
{
  $xml = ($level == 0) ? '<?xml version="1.0" encoding="ISO-8859-1"?>'.PHP_EOL : '';
  $tab = str_pad('', $level, '  ', STR_PAD_LEFT);

  foreach($array as $node => $value)
  {
    $xml .= "{$tab}<{$node}>";
    if(!is_array($value))
    {
      $xml .= $value;
    }
    else
    {
      $level++;
      $xml .= PHP_EOL.createXml($value, $level).$tab;
    }
    $xml .= "</{$node}>".PHP_EOL;
  }
  return $xml;
}

$xml = createXml($a);
echo $xml;
Buchow_PHP
  • 410
  • 3
  • 10
  • first one tanks for answers. I fixed my problem.and here is the code `code` function createXml($x) { $r = ''; foreach ($x as $key => $value) : $r .= (is_array($value)) ? "<$key>" . foreach_x($value) . "$key>" : "<$key>$value$key>"; endforeach; return $r; } `code` – omrcm Sep 11 '13 at 13:20
  • Your function will not work on arrays with more than 2 dimensions. Also there is no arbitrary function called 'foreach_x'. If this is a function you have created then why create two functions where one would suffice? Did you try the function suggested? – Buchow_PHP Sep 11 '13 at 13:54
  • yes i have try it and its work. and I have try it with 3 dimensions. I forget to change foreach_x to createXml. – omrcm Sep 11 '13 at 14:05