Jump to content

Need help with XML in PHP


raymak

Recommended Posts

Hello,

 

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:

 

<applications>

    <app appname="Notepad++" />

</applications>

 

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
https://forums.phpfreaks.com/topic/288945-need-help-with-xml-in-php/
Share on other sites

You need to append the app child to the root element

<?php
 
$doc = new DOMDocument("1.0");
$doc->formatOutput = true;
// Create root element
$root = $doc->createElement("Applications");
 
// Append the root element to the document
$doc->appendChild($root);
 
// 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();

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.