0

i created a XML document using DOMDocument and simpleXML. I need to add an attibute to the root element.

Below is how I created the document and the element. You will note that although the document is initally created by DOMDocument, the child/user nodes are created with simple XML.

$dom = new DOMDocument('1.0','UTF-8');

    /*** create the root element ***/ 
    $root = $dom->appendChild($dom->createElement( "Feed" )); 


    /*** create the simple xml element ***/ 
    $sxe = simplexml_import_dom( $dom ); 

    /*** add a user node ***/ 
    $firstChild = $sxe->addchild("FirstChild");  

I tried adding the attibutes to the root like this:

$root = $dom->appendData($dom->createAttribute("extractDate", "$now"));

but this does not work.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
Paul Kendal
  • 559
  • 9
  • 24
  • Why should have `DOMDocument::appendData()` (a method that doesn't even exist) worked? And which error and return value were you getting? You're hiding this important information from your question. Perhaps you were just getting an error? – hakre Aug 14 '15 at 20:34
  • possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – hakre Aug 14 '15 at 20:36

1 Answers1

-2

Using DOMDocument, you can set the attribute using the DOMElement::setAttribute method:

$dom = new DOMDocument('1.0','UTF-8');
$root = $dom->createElement("Feed");  
$attr = $root->setAttribute("extractDate", "$now"); // <-- here

$dom->appendChild($root);

For SimpleXML, you'll need to use the SimpleXMLElement::addAttribute method:

$sxe = simplexml_import_dom($dom);
$sxe->addAttribute("extractDate", "$now"); // <-- here
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156