N
N
Nikita karpov2021-01-06 18:27:43
PHP
Nikita karpov, 2021-01-06 18:27:43

How to export to xml?

Good evening . I wrote a script for exporting data from the database to an XML file, but the problem is that only 1 record is written.
Here is the result!

<?xml version="1.0"?>
<data>
  <time>21:16</time>
  <day>2021-01-26</day>
  <price>6000</price>
  <description>Delete project AND Serch a PHP learning</description>
</data>

Here is the php code
<?php 

include('connect.php');

  if (isset($_POST['xml'])) {
    
    $sql = mysqli_query($connection,'SELECT * FROM date');
    $dom = new domDocument('1.0');

    while($res = mysqli_fetch_assoc($sql)) {
      
      $time = substr($res['time'], 0 ,5);
      $dom->loadXML('<data>
  <time>'.$time.'</time>
  <day>'.$res['date'].'</day>
  <price>'.$res['price'].'</price>
  <description>'.$res['description'].'</description>
</data>');
        }
    
  }
file_put_contents('newxml.xml', $dom->saveXML());

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
my lord, 2021-01-06
@XBEHOLI

Have you been asked this question
Exporting data from MySQL to an XML file of a complex structure?

N
none7, 2021-01-06
@none7

loadXml doesn't work that way. In addition, there must be only one root element in an XML document, just as HTML cannot have two <html> tags. Example:

function getXmlRow($xml, $time, $day, $price, $description) {
    $names = array('time', 'day', 'price', 'description');
    $ret = $xml->createElement('date');
    foreach($names as $name){
        $ret->appendChild($xml->createElement($name, $$name));
    }
    return $ret;
}
$xml = new DomDocument('1.0', 'UTF-8');
$dates = $xml->createElement('dates');

for($i=0; $i <= 3; $i++)
    $dates->appendChild(getXmlRow($xml, '21:16', '2021-01-26', 6000, 'Delete project AND Serch a PHP learning'));

$xml->appendChild($dates);
echo $xml->saveXML();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question