从具有simplexml_load_string、循环和变量的哈希数组创建重复节点


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

我一直在研究这个问题,但我找不到我需要的东西。这应该不难,可能是语法问题=)

我在函数中创建一个表示 XML 的字符串,如下所示:

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

变量的内容是纯字符串,abc,def,ghi我以这种方式从哈希中获得的两个变量中

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);

当我使用 $sxe->asXml('xml/myGreatFile.xml'); 保存我的 XML 时,我得到了类似于以下内容的内容:

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

这很好,但现在对于我的新要求,我需要类似于这样的结果:

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

如何创建此重复节点?我尝试像连接变量一样在simplexml_load_string字符串中连接 PHP 函数,但似乎这是不可能的:

$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>
');

当然我的语法是错误的,但我想以某种方式创建这个重复的节点,也许有一个循环,也许直接使用我的哈希数组而不是将其传递给字符串。

答案很简单:在 simplexml 函数之外构建字符串变量,然后在函数中使用它。

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

如果您使用的是多维数组?只需嵌套您的foreach字符串构建语句即可。