Home > other >  Creating DOMDocument in PHP
Creating DOMDocument in PHP

Time:12-28

while ($row = $result->fetch()) {
  $dom = new DOMDocument;
  $element = $dom->createElement('div');
  $dom->appendChild($element);
  echo $dom->saveXML();
}

When I execute this code multiple times, something like this happens:

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

but I want the divs in a row like this:

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

for some reasons it is working with <button>.

CodePudding user response:

Your code needs some modification:

  1. It's better to create $dom and echo results outside the while loop. Because in your example you need just one DOM object.
  2. When trying to view the result using saveHTML instead of saveXML

There's lots of example here: https://www.php.net/manual/en/class.domdocument.php

$dom = new DOMDocument();  
while ($row = $result->fetch()) {
  $element = $dom->createElement('div');
  $dom->appendChild($element);
}
echo $dom->saveHTML();

CodePudding user response:

This works for me:

$document = new DOMDocument();
for ($i = 0; $i < 10; $i  ) {
    $element = $document->createElement('div');
    $document->appendChild($element);
}

echo $document->saveHTML();

Output (line formatted):

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
  • Related