0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

WHY? Tell me whyyyyy I didn't thought on this before?? XD I have been working too much u.u THANKS =)
It's more simple actually to build that with SimpleXML. Just noting. For some really advance mehtod including children, see: How to update SimpleXMLElement using array - just leaving it here for reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.