简体   繁体   中英

Using PHP DOM to create XML files from MySQL data

I have created a MySQL table and would like to save the contents of the table in an XML file for use by other applications. I can access the data fine and echo the data on a broswer window, but on saving using the DomDocument::save('thexmlfile.xml'), I cannot see any new files created in the directory location of the running PHP file.

you will have to create the dom xml from the mysql data and then save it in an xml file.An example:

$sql = 'select * from messages';
$run = mysql_query($sql, $link);

if( $run && mysql_num_rows( $run ) ) {
    $doc = new DOMDocument( '1.0' );
    $doc->formatOutput = true;
    $doc->preserveWhiteSpace = true;

    $root = $doc->createElement( 'data' );
    $doc->appendChild( $root );

    while( ( $fetch = mysql_fetch_assoc( $run ) )!== false ) {
        $node = $doc->createElement( 'node' );
        $root->appendChild( $node );

        foreach( $fetch as $key => $value ) {
            createNodes( $key, $value, $doc, $node );
        }
    }
    $doc->save("thexmlfile.xml");
}

function createNodes( $key, $value, $doc, $node ) {
    $key = $doc->createElement( $key );
    $node->appendChild( $key );
    $key->appendChild( $doc->createTextNode( $value ) );
}

Now, you should see the xml file.

Hope, it helps.

Hm, your question is about DOM , the accepted answer is about DOM , but you don't seem to need the capabilities of this, then libxml's brother SimpleXML seems much more straight forward... I assume your problem is long over, but just for completeness sake:

$sql = 'select * from messages';
$run = mysql_query($sql, $link);

if( $run && mysql_num_rows( $run ) ) {
    $xml = new SimpleXMLElement('<data/>');
    while($fetch = mysql_fetch_assoc($run)) {
        $node = $root->addChild('node');
        foreach( $fetch as $key => $value ) {
            $node->addChild($key,$value);
        }
    }
    $xml->asXML("thexmlfile.xml");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM