访问PHP生成的XML

时间:2012-06-06 19:10:43

标签: php xml

我正在以XML格式从MySQL数据库输出数据,因此我制作了一个php文件,在页面上以XML格式显示数据库中的数据。

<?php
// Return all existing nid in array (Different types of form);
function nid(){
    $query = "SELECT w.nid 
                FROM webform w";
    $result = mysql_query($query);
    $table = array();
    while ($row = mysql_fetch_row($result)){
        $table[] = $row[0];
    }
    return $table;
}

// Return existing rows of corresponding nid
function sid($nid){
    $query = "SELECT ws.sid 
                FROM webform_submissions ws 
                WHERE ws.nid = $nid";
    $result = mysql_query($query);
    $table = array();
    while ($row = mysql_fetch_row($result)){
        $table[] = $row[0];
    }
    return $table;  
}
// Return corresponding components of nid;
function cid($nid){
    $query = "SELECT wc.form_key 
                FROM webform_component wc 
                WHERE wc.nid = $nid
                ORDER BY wc.cid ASC";
    $result = mysql_query($query);
    $table = array();
    while ($row = mysql_fetch_row($result)){
        $table[] = $row[0];
    }
    return $table;  
}

// Return values of fields corresponding to nid and sid
function data($nid, $sid){
    $query = "SELECT wsd.data 
                FROM webform_submitted_data wsd 
                WHERE wsd.nid = $nid AND wsd.sid = $sid
                ORDER BY wsd.sid ASC";
    $result = mysql_query($query);
    $table = array();
    while ($row = mysql_fetch_row($result)){
        $table[] = $row[0];
    }
    return $table;      
}
// Define Constants
DEFINE("DB_SERVER", "localhost");
DEFINE("DB_USER", "root");
DEFINE("DB_PASS", "");
DEFINE("DB_NAME", "drupal7");

//Establish Connection
mysql_connect(DB_SERVER, DB_USER, DB_PASS)
    or die("Unable to connect to MySQL");

//Select Database
mysql_select_db(DB_NAME)
    or die("Could not connect to the database");

$xml_output = "<?xml version=\"1.0\" ?>\n";
$xml_output .= "<schema>";

foreach (nid() as $nid){
    $xml_output .= "<form fid=\"$nid\">\n";
    foreach (sid($nid) as $sid){
        $xml_output .= "<row rid=\"$sid\">\n";
        for ($i = 0; $i < count(cid($nid)); $i++){
            $tag_array = cid($nid);
            $value_array = data($nid, $sid);
            $tag_row = $tag_array[$i];
            $value_row = $value_array[$i];
            $xml_output .= "<$tag_row>\n";
            $xml_output .= "$value_row\n";
            $xml_output .= "</$tag_row>\n";
        }
        $xml_output .= "</row>\n";
    }
    $xml_output .= "</form>\n";
}
$xml_output .= "</schema>";

header("Content-type: text/xml");
echo $xml_output;
mysql_close();

?>

但我无法找到一种方法来访问XML数据或将其下载为XML文件。

以下是运行时输出的样子。 enter image description here

提前致谢

2 个答案:

答案 0 :(得分:1)

不要使用字符串来构建xml数据。你应该使用像SimpleXMLElement

这样的东西

请参阅How to generate XML file dynamically using PHP?

答案 1 :(得分:0)

而不是:

$table[] = $row[0];

尝试使用array_push函数:

array_push($table,$row[0]);