vishal vishal - 5 months ago 27
PHP Question

how to pass XML setAttribute in php foreach

I want to generate XML for an array which has many field and i want to set that fields in a single XML element as attributes of that element below is my php code.

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


But this is not working for me, it gives me an error like:

DOMElement:setAttribute() expects parameter 2 to be string,array given


My $rs array structure is like:


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

)


, i want output like:

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

Answer

You did some mistakes, the main of them that you appendchild element to Document but not to parent

$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