Jump to content

[SOLVED] DOMDocument Nesting Elements Unexpectedly


MrFish
 Share

Recommended Posts

Hello W3S, I'm trying to use DOMDocument but when i use appendChild its not appending to the element I expect it to. Here is a simple example-

$DOM = new DOMDocument();$DOM->appendChild($DOM->createElement("div"));$DOM->appendChild($DOM->createElement("div"));$DOM->appendChild($DOM->createElement("div"));$DOM->appendChild($DOM->createElement("div"));echo $DOM->saveXML();

What I expect-

<body>   <div></div>   <div></div>   <div></div>   <div></div></body>

What I get-

<body>   <div>	  <div>		 <div>			<div>			</div>		 </div>	  </div>   </div></body>

I've looked at the PHP documentation and this looks like how they did it but obviously I'm missing something. Can anyone spot my mistake? Edit: Also, i need to use createElement because I want to manipulate the elements before adding them. When you use new DOMElement() its read only for whatever reason

Edited by MrFish
  • Like 2
Link to comment
Share on other sites

That's the same code I used as posted in OP. I checked an old file I used on this same server which printed correctly. Started stripping it down and found it started nesting incorrectly after I took out text nodes. This now works-

$DOM = new DOMDocument();  $div = $DOM->createElement("div");  $div->appendChild($DOM->createTextNode(""));$DOM->appendChild($div);  $div = $DOM->createElement("div");  $div->appendChild($DOM->createTextNode(""));$DOM->appendChild($div);  $div = $DOM->createElement("div");  $div->appendChild($DOM->createTextNode(""));$DOM->appendChild($div);  $div = $DOM->createElement("div");  $div->appendChild($DOM->createTextNode(""));$DOM->appendChild($div);echo $DOM->saveXML();

But it seems like a cheap trick. How does this page look for you? [ URL REMOVED ] Edit: Oh wait you're right. I was viewing the page through Chromes element inspector. In the HTML it's <div/> like you said. This doesn't register as <div></div> though. Any idea how to make that print differently without text nodes?

Edited by MrFish
Link to comment
Share on other sites

Solved The answer is simply to use $DOM->saveHTML() instead of $DOM->saveXML() Simple enough. Thanks for your help :D

Link to comment
Share on other sites

Using saveHTML() can be problematic if what you're outputting is XML, although in your case, it doesn't seem like it.In case you do need to use XML (for the sake of, let's say nesting SVG), you can have the output you want by passing an option to saveXML(), like:

$DOM->saveXML(null, LIBXML_NOEMPTYTAG);

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...