如何使用PHP simpleXML从数据库回显此XML数据?

时间:2013-01-27 03:26:03

标签: php xml wordpress simplexml

我在Wordpress中使用formbuilder插件,它将表单输入作为XML数据提交给数据库。现在我想获取该数据并将其显示在另一页面中。我已经开始尝试使用simpleXML来实现这一目标,但现在我遇到了一个障碍。

数据库每行中显示的XML数据遵循以下格式:

<form>
    <FormSubject>Report</FormSubject>
    <FormRecipient>****@***.com</FormRecipient>
    <Name>admin</Name>
    <Department>test</Department>
    <Value>1000</Value>
    <Comments>test</Comments>
    <Page>http://***.com</Page>
    <Referrer>http://****.com</Referrer>
</form>

我之前已经设法从数据库中相同标记的XML字符串中使用simpleXML获取我需要的数据但现在我的问题是,如何使用数据库中每一行的循环执行此操作?

运行以下代码时,wordpress会显示一个空白页面,表示存在错误:

<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$string = $statistic->xmldata
$xml = simplexml_load_string($string);
$Name = (string) $xml->Name;
$Department = (string) $xml->Department;
$Value = (string) $xml->Value;
$Comments = (string) $xml->Comments;

echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";

?>

2 个答案:

答案 0 :(得分:2)

你失踪了;在第5行

$string = $statistic->xmldata

应该是

$string = $statistic->xmldata;

您应该考虑在wp-config.php文件中启用WP_DEBUG常量。将以下代码插入到wp-config.php中,就在/ *之前,就是这样,停止编辑!快乐的博客。 * /

define('WP_DEBUG', true);

/* That's all, stop editing! Happy blogging. */

有关调试的更多提示,请阅读codex

Formbuilder用户自定义函数在formbuilder_xml_db_results中提取XML数据类:

function xmltoarray($xml)
    {
        $xml = trim($xml);

        $match = "#<([a-z0-9_]+)([ \"']*[a-z0-9_ \"']*)>(.*)(</\\1>)#si";
        $offset = 0;

        if(!preg_match($match, $xml, $regs, false, $offset)) {
            return($xml);
        }

        while(preg_match($match, $xml, $regs, false, $offset))
        {
            list($data, $element, $attribs, $content, $closing) = $regs;
            $offset = strpos($xml, $data) + strlen($data);

            $tmp = $this->xmltoarray($content);
            $result[$element] = $tmp;

        }

        return($result);
    }

在代码中定义该函数(在全局$ wpdb之前;您不必担心在Class中定义该函数的名称),而不是以这种方式修改代码:

<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$xml = xmltoarray( $statistic->xmldata );
$Name = (string) $xml['form']['Name'];
$Department = (string) $xml['form']['Department'];
$Value = (string) $xml['form']['Value'];
$Comments = (string) $xml['form']['Comments'];

echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";

?>

编辑:编辑$ xml ['评论']到$ xml ['form'] ['评论']和类似的

答案 1 :(得分:0)

我通过使用stripslashes()

从XML字符串中删除反斜杠来修复它