使用php将表格数据(mysql)转换为xml

时间:2013-12-04 09:21:55

标签: php xml

我有一个包含一些表格的My SQL数据库。现在我想从表中提取该数据并将其以XML格式提供。

<?php
    $username = "root";
    $password = "";
    $hostname = ""; 

    //connection to the database
    $dbhandle = mysqli_connect($hostname, $username, $password,"examples" ); 
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    } else
        echo "Connected to MySQL<br>";

    $xml          = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; 
    $root_element = "car"."s"; //fruits 
    $xml         .= "<$root_element>";

    //execute the SQL query and return records
    $result = mysqli_query($dbhandle,"SELECT id, name,year FROM cars");
    if (!$result) {
        printf("Error: %s\n", mysqli_error($dbhandle));
        exit();
    }

    if(mysqli_num_rows($result)>0) {    
        while($result_array = mysqli_fetch_assoc($result)) {
            $xml .= "<car>";   
            //loop through each key,value pair in row    
            foreach($result_array as $key => $value) {          
                //$key holds the table column name  
                $xml .= "<$key>";          
                //embed the SQL data in a CDATA element to avoid XML entity issues 
                $xml .= "<![CDATA[$value]]>";            
                //and close the element          
                $xml .= "</$key>";   
            }         
            $xml.="</car>";    
        } 
    } 

    $xml .= "</$root_element>";   
    //send the xml header to the browser header
    ("Content-Type:text/xml");   
    //output the XML data 
    echo $xml;

    //fetch tha data from the database 
    /*while ($row = mysqli_fetch_array($result)) {
        echo $row['id']." ".$row['name']." ". $row['year'];
        echo"<br>";
    }*/
    //close the connection
    mysqli_close($dbhandle);

?>

但是,我收到了以下错误。

The XML page cannot be displayed  Cannot view XML input using style

片。请更正错误,然后单击“刷新”按钮,或稍后重试。


Invalid at the top level of the document. Error processing resource 'http://.... my%20portable%20files/mysqlxml.php'. ... Connected to MySQL<br><?xml version="1.0" encoding="UTF-8"?><cars><car><id><![CDATA[1]]>...`
你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

echo "Connected to MySQL"; 

部分可能会干扰XML输出。请注意,在输出XML时,您必须输出xml而不输出任何内容:没有空格,没有文本,在初始XML标记之前没有任何内容(然后是根节点,然后是其余部分)。

另外,我没有看到标题输出正确,请尝试:

header("Content-Type:text/xml");

如果必须,还要添加您的编码。

如果全部失败,请发布一个链接,以便我们看到输出并调试问题。