1

I was tesing with a simple example of how to display XML in browser using PHP and found this example which works good

<?php
$xml = new DOMDocument("1.0");

$root = $xml->createElement("data");
$xml->appendChild($root); 
$id   = $xml->createElement("id");
$idText = $xml->createTextNode('1');
$id->appendChild($idText);
$title   = $xml->createElement("title");
$titleText = $xml->createTextNode('Valid');
$title->appendChild($titleText);
$book = $xml->createElement("book");
$book->appendChild($id);
$book->appendChild($title);
$root->appendChild($book);

$xml->formatOutput = true;
echo "<xmp>". $xml->saveXML() ."</xmp>";
$xml->save("mybooks.xml") or die("Error");
?>

It produces the following output:

<?xml version="1.0"?>
<data>
  <book>
    <id>1</id>
    <title>Valid</title>
  </book>
</data>

Now I have got two questions regarding how the output should look like.

  1. The first line in the xml file '', should not be displayed, that is it should be hidden

  2. How can I display the TextNode in the next line. In total I am exepecting an output in this fashion

    <data>
      <book>
        <id>1</id>
        <title>
          Valid
        </title>
      </book>
    </data>
    

Is that possible to get the desired output, if so how can I accomplish that.

Thanks

1

2 Answers 2

1

To skip the XML declaration you can use the result of saveXML on the root node:

$xml_content = $xml->saveXML($root);
file_put_contents("mybooks.xml", $xml_content) or die("cannot save XML");

Please note that saveXML(node) has a different output from saveXML().

Sign up to request clarification or add additional context in comments.

Comments

0

First question: here is my post where all usable threads with answers are listed: How do you exclude the XML prolog from output?

Second question: I don't know of any PHP function that outputs text nodes like that.

You could:

  • read xml using DomDocument and save each node as string
  • iterate trough nodes
  • detect text nodes and add new lines to xml string manually

At the end you would have the same XML with text node values in new line:

<node>
    some text data
</node>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.