Get MySQL database output via PHP to XML

前端 未结 5 949
失恋的感觉
失恋的感觉 2020-11-27 17:37

I have a MySQL database on my website, and I would like to know how I could get an XML output via PHP of the following columns in the table:

  1. udid
  2. coun
5条回答
  •  执笔经年
    2020-11-27 18:25

    I struggle a lot to find out this solution in mysqli format but nowhere i found the solution. Below is the solution i figured. Hope it will help some one.

    connect_errno) {
        throw new Exception(sprintf("Mysqli: (%d): %s", $mysql->connect_errno, $mysql->connect_error));
    }
    
    //Extract data to export to XML
    $sqlQuery = 'SELECT * FROM t1';
    if (!$result = $mysql->query($sqlQuery)) {
        throw new Exception(sprintf('Mysqli: (%d): %s', $mysql->errno, $mysql->error));
    }
    
    //Create new document 
    $dom = new DOMDocument;
    $dom->preserveWhiteSpace = FALSE;
    
    //add table in document 
    $table = $dom->appendChild($dom->createElement('table'));
    
    //add row in document 
    foreach($result as $row) {
        $data = $dom->createElement('row');
        $table->appendChild($data);
    
        //add column in document 
        foreach($row as $name => $value) {
    
            $col = $dom->createElement('column', $value);
            $data->appendChild($col);
            $colattribute = $dom->createAttribute('name');
            // Value for the created attribute
            $colattribute->value = $name;
            $col->appendChild($colattribute);           
        }
    }
    
    /*
    ** insert more nodes
    */
    
    $dom->formatOutput = true; // set the formatOutput attribute of domDocument to true 
    // save XML as string or file 
    $test1 = $dom->saveXML(); // put string in test1
    $dom->save($filename); // save as file
    $dom->save('xml/'.$filename);   
    ?>
    

提交回复
热议问题