Search code examples
phpxmlhashmultidimensional-arraysimplexml

Creating a repetitive node from a hash array with simplexml_load_string, a cycle and variables


I've been researching this problem, but I can't find what I need. It shouldn't be difficult, probably it's a matter of syntax =)

I create a string representing an XML inside the function like this:

$sxe = simplexml_load_string('
<xmlFile>
 <item param="'.$variable.'">
  <subitem>'.$var2s.'</subitem>
 </item>
</xmlFile>
');

The contents of the variables are plain strings like this abc,def,ghi in both variables which I obtain from a hash this way:

isset($variable);
$variable="";
isset($vars2);
$vars2="";

foreach ($hashArray as $stringKey => $stringValue) {
 // I separate each result with a comma
 $variable .= $stringKey.",";
 $vars2 .= $stringValue.",";
}
// Then remove the last comma
$variable = substr($variable, 0, -1);
$vars2 = substr($vars2, 0, -1);

When I save my XML with $sxe->asXml('xml/myGreatFile.xml'); I got something similar to:

<xmlFile>
 <item param="abc,def,ghi">
  <subitem>JKL,MNO,PQR</subitem>
 </item>
</xmlFile>

That was fine but now for my new requirement I need a result similar to this:

<xmlFile>
 <item param="abc">
  <subitem>JKL</subitem>
 </item>
 <item param="def">
  <subitem>MNO</subitem>
 </item>
 <item param="ghi">
  <subitem>PQR</subitem>
 </item>
</xmlFile>

How can I create this repetitive node? I tried to concatenate PHP functions inside the simplexml_load_string string as I did with the variables but seems to be it's not possible:

$sxe = simplexml_load_string('
<xmlFile>'.
 // Syntax Error u_u
 foreach ($hashArray as $stringKey => $stringValue) {
  $variable .= $stringKey.",";
  $vars2 .= $stringValue.",";.
 
 '<item param="'.$variable.'">
  <subitem>'.$var2s.'</subitem>
 </item>'.
 }
.'</xmlFile>
');

Of course my syntax it's wrong, but I want to create this repetitive node somehow, maybe with a cycle and maybe using my hash array directly instead of passing it to string.


Solution

  • The answer is pretty simple: build your string variable outside of the simplexml function and then use it in the function.

      $mystring = "<xmlFile>";
      foreach($array as $key => $value)
      {
          $mystring .= "<item param='$key'><subitem>$value</subitem></item>";
      }
      $mystring .= "</xmlFile>";
    
      $sxe = simplexml_load_string($mystring);
    

    And if you're using a multidimensional array? Just nest your foreach string building statements.