Using PHP DOM to create XML files from MySQL data

前端 未结 2 1543
醉话见心
醉话见心 2020-12-22 05:26

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

相关标签:
2条回答
  • 2020-12-22 06:09

    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.

    0 讨论(0)
  • 2020-12-22 06:10

    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");
    }
    
    0 讨论(0)
提交回复
热议问题