I am new in creating XML file using php..I wrote a code but the code doesnot show xml file on running it..Can anybody figure out what the problem is

the code is as follows

<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$root=$dom->createElement("xml");
$dom->appendChild($root);
$title=$dom->createElement("title");
$root->appendChild($title);
$path=$dom->createElement("path");
$title->appendChild($path);
$title=$dom->createTextNode("pepperoni");
$path->appendChild($title);
echo $dom->saveXML();

?>

i want to get output as

<xml>-as root
<title>
<path>pepperoni</path>
</title>
</xml>

Recommended Answers

All 3 Replies

Two points to note: DOMDocument::saveXML() returns either an XML string, or false on failure.

To test if an error occurred, try var dumping the result. E.g.:

var_dump($dom->saveXML());

If this is boolean false, then you have an error.

Otherwise, the method will have returned an XML string. As such, you cannot just echo out the response and expect to see it. You need to set the correct response headers. E.g.:

header('Content-Type: text/xml');
echo $dom->saveXML();

Two points to note: DOMDocument::saveXML() returns either an XML string, or false on failure.

To test if an error occurred, try var dumping the result. E.g.:

var_dump($dom->saveXML());

If this is boolean false, then you have an error.

Otherwise, the method will have returned an XML string. As such, you cannot just echo out the response and expect to see it. You need to set the correct response headers. E.g.:

header('Content-Type: text/xml');
echo $dom->saveXML();

while using var_dump i got the result as

string '<?xml version="1.0" encoding="UTF-8"?>
<xml><title><path>pepperoni</path></title></xml>
' (length=88)

what should i do???????
i should also get it as ordered one like
<xml>
<title>
<path>pepperoni</path>

Okay, so that obviously isn't returning an error. So as per my first post, set the response headers before echoing the XML.

header('Content-Type: text/xml');
echo $dom->saveXML();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.