如何在XML中插入PHP数组?

时间:2012-12-24 21:08:08

标签: php xml arrays foreach

大家好,我有一点问题,我有一个像这样的数组

$slike=array('1.jpg','2.jpg')

另一个看起来像这样的XML

<?xml version='1.0' encoding='UTF-8'?>
<settings>
<show_context_menu>yes</show_context_menu>
<hide_buttons_delay>2</hide_buttons_delay>
<thumbs_width>200</thumbs_width>
<horizontal_space_btween_buttons>0</horizontal_space_btween_buttons>
<buttons_margins>0</buttons_margins>
</settings>

如何在该XML中插入$ slike,新XML如下所示:

<?xml version='1.0' encoding='UTF-8'?>
<settings>
<show_context_menu>yes</show_context_menu>
<hide_buttons_delay>2</hide_buttons_delay>
<thumbs_width>200</thumbs_width>
<horizontal_space_btween_buttons>0</horizontal_space_btween_buttons>
<buttons_margins>0</buttons_margins>
<image>1.jpg</image>
<image>2.jpg</image>
</settings>

提前Txanks

3 个答案:

答案 0 :(得分:1)

不知道你运行了哪个问题,但是使用XML库相当简单,例如:即使在你的情况下使用SimpleXML:

$slike = array('1.jpg','2.jpg');
$name = 'image';

$doc = new SimpleXMLElement($xml);
foreach($slike as $file) {
    $doc->addChild($name, $file);
}

echo $doc->asXML();

此示例中的$xml是您问题中的xml字符串。输出:

<?xml version="1.0" encoding="UTF-8"?>
<settings>
<show_context_menu>yes</show_context_menu>
<hide_buttons_delay>2</hide_buttons_delay>
<thumbs_width>200</thumbs_width>
<horizontal_space_btween_buttons>0</horizontal_space_btween_buttons>
<buttons_margins>0</buttons_margins>
<image>1.jpg</image><image>2.jpg</image></settings>

答案 1 :(得分:0)

这样的事情:

header("Content-Type: text/xml; charset=utf-8");  // added this line - that way the browser will render it as XML
$slike = array('1.jpg','2.jpg');

$xml = "<?xml version='1.0' encoding='UTF-8'?>
<settings>
<show_context_menu>yes</show_context_menu>
<hide_buttons_delay>2</hide_buttons_delay>
<thumbs_width>200</thumbs_width>
<horizontal_space_btween_buttons>0</horizontal_space_btween_buttons>
<buttons_margins>0</buttons_margins>";

foreach($slike as $s){
    $xml.= "<image>".$s."</image>"; // create a new <image> node for each image in array
}


$xml .= "</settings>";

print_r($xml);

输出:

<?xml version='1.0' encoding='UTF-8'?>
<settings>
    <show_context_menu>yes</show_context_menu>
    <hide_buttons_delay>2</hide_buttons_delay>
    <thumbs_width>200</thumbs_width>
    <horizontal_space_btween_buttons>0</horizontal_space_btween_buttons>
    <buttons_margins>0</buttons_margins>
    <image>1.jpg</image>
    <image>2.jpg</image>
</settings>

答案 2 :(得分:0)

http://php.net/manual/en/book.simplexml.php

对于您的示例,语法看起来像这样

<aaaa Version="1.0">
   <bbb>
     <cccc>
       <dddd Id="id:pass" />
       <eeee name="hearaman" age="24" />
     </cccc>
   </bbb>
</aaaa>

 $xml = new SimpleXMLElement($xmlString);
    echo $xml->bbb->cccc->dddd['Id'];
    echo $xml->bbb->cccc->eeee['name'];
    // or...........
    foreach ($xml->bbb->cccc as $element) {
      foreach($element as $key => $val) {
       echo "{$key}: {$val}";
      }
    }