Jump to content

Need help with XML in PHP

Go to solution Solved by boompa,

Recommended Posts



I am trying to generate XML file and print the xml value in the browser. I am having had time create child element and adding attribute inside the child element.


Structure I am trying to create is:



    <app appname="Notepad++" />



Here is the code I'm trying to accomplish the above format:

$doc = new DOMDocument("1.0");
$doc->formatOutput = true;
$main = $doc->createElement("Applications");
$doc->appendChild( $main);
	$child = $doc->createElement( "app" );	
	$attr = $doc->appendChild($child);
	$attr->setAttribute("AppName", "NotePad++");
echo $doc->saveXML();

I am not sure what I'm doing wrong, but I get below error when I browse the php page:


The XML page cannot be displayed

Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.

Only one top level element is allowed in an XML document. Error processing resource 'http://localhost/servers/xmldoc.php'. ...

<app AppName="NotePad++"/>-^
Link to comment
Share on other sites

  • Solution

You need to append the app child to the root element

$doc = new DOMDocument("1.0");
$doc->formatOutput = true;
// Create root element
$root = $doc->createElement("Applications");
// Append the root element to the document
// Create the child element
$child = $doc->createElement( "app" );
// Append the child to the root element
$attr = $root->appendChild($child);
$attr->setAttribute("AppName", "NotePad++");
echo $doc->saveXML();
Edited by boompa
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.