3

任何能回答我的问题的人都应该获得巨大的超凡金牌!

我正在尝试将 MySQL 表的内容转换为一种漂亮、简单的 XML 格式。我正在运行一些运行良好的 PHP,我可以看到 XML(美好时光)。但是,在 MySQL 表中,有几个字段填充了非编码的 HTML 表代码。我将每个字段值包装在 CDATA 标记中,我确保 xml 标记已关闭,但我想知道我是否遗漏了某些内容,因为它出错了,我不明白为什么(坏次)。对我来说它看起来不错,所以我尝试在 Excel 中打开它(因为这就是客户端会看到它的方式)它声称“包”的开始标签与“long_description”的结束标签匹配。

http://www.shavesgreensafaris.com/display.php是我正在处理的页面,因此您可以在那里查看数据。

这是我正在使用的代码...

        $xml          = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        $root_element = "packages";
        $xml         .= "<$root_element>";


        if(mysql_num_rows($result)>0)
        {
           while($result_array = mysql_fetch_assoc($result))
           {
              $xml .= "<package>";

              //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.="</package>";
           }
        }

//close the root element
$xml .= "</$root_element>";

//send the xml header to the browser
header ("Content-Type:text/xml"); 

//output the XML data
echo $xml;

我到底做错了什么?!


编辑

好的,所以似乎有些东西从第 310 行周围的 long_description 标记中删除了一个“<” - 如果您想将其视为“>long_description>”,您可以在视图源中搜索 - 发生了一些非常奇怪的事情,并且标签没有正确形成。我不完全确定这是如何发生的,因为我使用的代码肯定会在所有 $keys 上放置左尖括号和右尖括号。它只发生一次,但它似乎把其他一切都塞满了。

有谁知道为什么会发生这种情况?

非常感谢任何帮助,并在此先感谢!

宝石

4

1 回答 1

2

我觉得DOM将是解决这个问题的方法。乍一看,该代码可能看起来有些麻烦,但它会为您处理所有输出格式:

<?php

  // The names of the root node and the node that will contain a row
  $root_element = "packages";
  $row_element = "package";

  // Create the DOMDocument and the root node
  $dom = new DOMDocument('1.0', 'utf-8');
  $rootNode = $dom->appendChild($dom->createElement($root_element));

  // Loop the DB results
  while ($row = mysql_fetch_assoc($result)) {

    // Create a row node
    $rowNode = $rootNode->appendChild($dom->createElement($row_element));

    // Loop the columns
    foreach ($row as $col => $val) {

      // Create the column node and add the value in a CDATA section
      $rowNode->appendChild($dom->createElement($col))
              ->appendChild($dom->createCDATASection($val));

    }

  }

  // Output as string
  echo $dom->saveXML();
于 2012-06-22T11:28:08.483 回答