如何在php foreach中传递XML setAttribute

drnojrws  于 2022-12-10  发布在  PHP
关注(0)|答案(3)|浏览(135)

我想为一个有许多字段数组生成XML,并将单个XML元素中的字段设置为该元素的属性。

<?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>
tez616oj

tez616oj1#

您犯了一些错误,主要是您将子元素附加到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

ct2axkht

ct2axkht2#

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

foreach( $rs as $key => $value ){
    $attrib=$doc->createAttribute($key);
    $attrib->nodeValue=$value;
    $fs->appendChild( $attrib );    
}
0lvr5msh

0lvr5msh3#

$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>

相关问题