如何使用带有条件嵌套的PHP和MYSQL创建XML

时间:2014-12-02 22:08:21

标签: php mysql xml

我试图通过使用数据库通过MYSQL和PHP创建XML文件制作电视指南。到目前为止,我取得了很好的成功,并设法输出了每天的各种渠道。

问题是当我尝试将各种程序引入时。在数据库中,每个程序分配一天,并显示通道。但是,生成的XML每天都会将每个程序放在每个通道上。

这是我到目前为止所做的:

$xml = new DOMDocument("1.0", "UTF-8");
$xml->formatOutput = TRUE;

$day_query = "SELECT day_name FROM day;";

$dq_result = mysql_query($day_query) or die(mysql_error());

$tvguide = $xml->createElement("guide");
$tvguide = $xml->appendChild($tvguide);

    if($dq_result)
    while($dayrow = mysql_fetch_row($dq_result)){
        $day = $xml->createElement("day");
        $day->setAttribute("name", $dayrow[0]);
        $day = $tvguide->appendChild($day);

        $channel_query = "SELECT channel_ID, channel_Name FROM channel ORDER BY channel_Name ASC;";

        $cq_result = mysql_query($channel_query) or die(mysql_error());

        if($cq_result)
            while($channelrow = mysql_fetch_row($cq_result)){

            $channel = $xml->createElement("channel");
            $channel->setAttribute("id", $channelrow[0]);
            $channel = $day->appendChild($channel);

            $channel_name = $xml->createElement("channel_name");
            $channelNameText = $xml->createTextnode($channelrow[1]);
            $channel_name->appendChild($channelNameText);
            $channel_name = $channel->appendChild($channel_name);


            $show_query = "SELECT programme_ID, programme_Name, start_Time, duration, description, day_Name, channel_Name FROM programme ORDER BY start_Time ASC;";

            $sq_result = mysql_query($show_query) or die(mysql_error());

            if($sq_result)
                while($showrow = mysql_fetch_row($sq_result)){


            $show = $xml->createElement("show");
            $show = $channel->appendChild($show);

            $show_name = $xml->createElement('show_name');
            $show_name->setAttribute("id", $showrow[0]);
            $showNameText = $xml->createTextnode($showrow[1]);
            $show_name->appendChild($showNameText);
            $show->appendChild($show_name);



            }

        }
}

基本上,我想知道如何嵌套所有day_Name等于星期一的节目,例如,在'Monday'XML标签内。谢谢。

1 个答案:

答案 0 :(得分:1)

好的,快速回答你的问题,就像改变一样简单:

  

$ show_query =“SELECT programme_ID,programme_Name,start_Time,duration,description,day_Name,channel_Name FROM program ORDER BY start_Time ASC;”;

  

$ show_query =“SELECT programme_ID,programme_Name,start_Time,duration,description,day_Name,channel_Name FROM program WHERE day_Name ='$ dayrow [0]'AND channel_Name ='$ channelNameText'ORDER BY start_Time ASC;”;

但是,还有一些事情需要改变:

  1. 您不应使用mysql_界面,使用mysqliPDO_mysql
  2. 你正在做一个不变的查询(SELECT channel_ID, channel_Name FROM channel ORDER BY channel_Name ASC;)。你可能只应该在一段时间之前做一次,然后缓存它的结果。