How to define the output format of an XML in PHP?

Asked

Viewed 117 times

1

Good afternoon!

I’m developing a webservice in which I will not disclose the name in which there is a method that accepts XML in the following mode:

<exemplo>
   <exemplo></exemplo>
   <exemplo></exemplo>
</exemplo>

I am creating XML’s by Domdocument but I can not generate XML’s as above, always comes out in this format children who have no values: <exemplo/> and this generates errors in the webservice not returning what I need.

Is there any way that output is generated by DOM?

Follow how I raise my children.

$exemplo = $dom->createElement("exemplo","");
$root->appendChild($exemplo);

1 answer

1


Do as follows below, using the option of LIBXML_NOEMPTYTAG as the second parameter in the method saveXML:

<?php

$dom = new DOMDocument( "1.0", "ISO-8859-15" );

$root = $dom->createElement("root","");

$exemplos = $dom->createElement("exemplo","");

$exemplo1 = $dom->createElement("exemplo","");
$exemplo2 = $dom->createElement("exemplo","");
$exemplo3 = $dom->createElement("exemplo","");

$exemplos->appendChild($exemplo1);
$exemplos->appendChild($exemplo2);
$exemplos->appendChild($exemplo3);

$root->appendChild($exemplos);

echo $dom->saveXML($root, LIBXML_NOEMPTYTAG);

Output:

<root><exemplo><exemplo></exemplo><exemplo></exemplo><exemplo></exemplo></exemplo></root>

Example: example of use.

  • 1

    Wow it’s so simple and I didn’t even know! kkkk until I’ll use this answer to my problems!

  • 1

    And in case you want to use DOM to add attributes?

  • Just use the $dom->createAttribute method and then add a value to it, and finally add it to the element you want.

  • 1

    You have an example here: http://ideone.com/DWbaZQ

  • Thanks :) now yes I can continue using XML for some api’s

  • 1

    Excellent, it worked!!! Thank you very much!!!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.