0

My attempt to create a xml file is nearly completed, but I have one or two snags.

The data is pulled from a DB via mysql_connect()

$sql = "SELECT `entity_id`,`name` FROM `table`

The desired output is:

<?xml version="1.0" encoding="utf-8"?>
<content>
    <item>
        <id>1</id>
        <name><![CDATA[name1]]</name>
    </item>
    <item>
        <id>2</id>
        <name><![CDATA[name2]]</name>
    </item>
</content>

Now I have been trying to do this via DOMDocument but I can't get the indent correct

$doc = new DOMDocument( '1.0', 'utf-8' );
$ele = $doc->createElement( 'content' );

    while ($row = mysql_fetch_assoc($res)) {

    $ele = $doc->createElement( 'id' );
    $ele->nodeValue = $row['entity_id'];
    $doc->appendChild( $ele );

    $ele = $doc->createElement( 'name' );
    $ele->nodeValue = $row['name'];
    $doc->appendChild( $ele );

    };

$doc->appendChild( $ele );
$doc->save('MyXmlFile.xml');

but this outputs:

<?xml version="1.0" encoding="utf-8"?>
    <id>1</id>
    <name>name1</name>
    <id>2</id>
    <name>name2</name>

How do I put the results to a child level? (main problem) and after that I have to figure out how to wrap a CDATA tag around the textual data?

Jacco
  • 86
  • 7

1 Answers1

0

Did go the XMLWriter route to fix this:

$xml = new XMLWriter();

$xml->openURI('myxmlfile.xml');
$xml->startDocument('1.0', 'utf-8');
$xml->setIndent(true);
$xml->startElement('content');

while ($row = mysql_fetch_assoc($res)) {

    $xml->startElement('item');

        $xml->startElement("id");
        $xml->writeRaw("$row['entity_id']);
        $xml->endElement();

        $xml->startElement("name");
        $xml->writeCData(utf8_encode ($row['name']));
        $xml->endElement();

    $xml->endElement();
    }

$xml->endElement();

$xml->flush();
Jacco
  • 86
  • 7