如何在php foreach中传递XML setAttribute

时间:2016-07-06 07:05:08

标签: php xml

我想为一个有很多字段的数组生成XML,我想在单个XML元素中设置这些字段,因为下面那个元素的属性是我的php代码。

<?php
$rs=array();//values come in $rs from database, it has many fields
$doc = new DOMDocument(); 
$doc->formatOutput = true; 
$root = $doc->createElement( "slides" ); 
$doc->appendChild( $root );
$firstchild = $doc->createElement( "device" ); 
$fs=$doc->appendChild( $firstchild );
foreach( $rs as $key=>$value ){           
    $fs->setAttribute($key,$value);
}
$xml_string = $doc->saveXML();
echo $xml_string;

但这不适合我,它给我一个错误,如:

DOMElement:setAttribute()期望参数2为字符串,给定数组

  

我的$ rs数组结构如下:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => dfd
            [width] => 2
            [height] => 1
            [resolution] => 
            [space] => 
        )

)

,我希望输出如下:

<slides>
    <device id="12" name="mydevice" color="red" .....and so on></device>
</slides>

3 个答案:

答案 0 :(得分:1)

你犯了一些错误,其中主要是你将appendchild元素添加到Document而不是父

$doc = new DOMDocument(); 
$doc->formatOutput = true;

$root = $doc->createElement( "slides" ); 
$doc->appendChild( $root );

$fs = $doc->createElement( "device" ); 
$root->appendChild( $fs );

foreach( $rs as $key=>$value ){           
    $fs->setAttribute($key,$value);
}

$xml_string = $doc->saveXML();
echo $xml_string;

working example

答案 1 :(得分:0)

您需要创建每个属性并将其分配给正确的节点,如下所示:

nav.add_branch(
'containers_pods',
{
    'containers_pod':
    [
        lambda ctx: list_tbl.select_row_by_cells(
            {'Name': ctx['pod'].name, 'Provider': ctx['provider'].name}),
        {
            'containers_pod_edit_tags':
            lambda _: pol_btn('Edit Tags'),
        }
    ],
    'containers_pod_detail':
    [
        lambda ctx: list_tbl.click_row_by_cells(
            {'Name': ctx['pod'].name, 'Provider': ctx['provider'].name}),
        {
            'containers_pod_timelines_detail':
            lambda _: mon_btn('Timelines'),
            'containers_pod_edit_tags_detail':
            lambda _: pol_btn('Edit Tags'),
        }
    ]
}

答案 2 :(得分:0)

$ rs变量是一个记录数组,其中字段数组作为元素。所以你需要两个嵌套循环。

外部循环迭代记录并为每条记录创建一个device元素节点。内循环迭代字段并添加属性。

$rs = [
  [ 
    'id' => 1,
    'name' => 'dfd',
    'width' => 2,
    'height' => 1,
    'resolution' => '',
    'space' => ''
  ]
];

$document = new DOMDocument(); 

$slides = $document->appendChild(
  $document->createElement("slides")
);

foreach ($rs as $record) {
  $device = $slides->appendChild(
    $document->createElement("device")
  );
  foreach($record as $key => $value){           
    $device->setAttribute($key,$value);
  }
}

$document->formatOutput = true;
echo $document->saveXML();

输出:

<?xml version="1.0"?>
<slides>
  <device id="1" name="dfd" width="2" height="1" resolution="" space=""/>
</slides>