Search code examples
phpmysqlxmlxmldom

Create xml file from mysql


Found this script what nearly does what I want; But not all the way.

$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;

$table = $dom->appendChild($dom->createElement('incidents'));

foreach($result as $row) {
$data = $dom->createElement('incident');
$table->appendChild($data);

foreach($row as $name => $value) {

    $col = $dom->createElement('column', $value);
    $data->appendChild($col);
    $colattribute = $dom->createAttribute('name');

    $colattribute->value = $name;
    $col->appendChild($colattribute);

It now gives an xml result with:

<column name="id"> and </column>

I would like this to be

<id> and </id> 

What do I have to changed? I've tried all the options I can think of.

This is only the middle part. The rest seems to work fine.

Thanks in advance!


Solution

  • The function createElement does exactly this - creates new element.
    The first parameter will be the name of your element (in your case - column):

    $col = $dom->createElement('column', $value);
    

    If you want to have an element with the name id you should use the id as the name of the element:

    $col = $dom->createElement('id', $value);
    

    Update - a better explanation:

    The function createElement gets 2 parameters. The first parameter is the name of the tag, the second parameter is the content of the tag.
    This mean that if you do:

    $col = $dom->createElement('ThisIsMySpecialTagName', 'ValueValueValue');
    

    You will get

    <ThisIsMySpecialTagName>ValueValueValue</ThisIsMySpecialTagName>
    

    You can put in the first parameter whatever you want the name of the tag (the thing that comes between < and >) and the second parameter is the content of the tag (what comes between the opening and the closing tag).