PHP将XML文件导入数据库

时间:2013-05-04 04:40:56

标签: php xml simplexml

我试图允许用户上传文件,然后使用SimpleXML将其内容读入数据库。我的代码如下:

else
{
    $info = pathinfo($_FILES['xml_file']['tmp_name']);
    $extension = $info['extension'];

    if($extension != 'xml')
    {
        flash_message($lang->wiki_invalid_file, 'error');
        admin_redirect('index.php?module=wiki-import');
    }
    else
    {
        if($_FILES['xml_file']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['xml_file']['tmp_name']))
        {
            $string = file_get_contents($_FILES['xml_file']['tmp_name']);
            $xml = new SimpleXMLElement($string);
            foreach($xml->article as $article)
            {
                $query = "INSERT INTO " . TABLE_PREFIX . "wiki('authors','title','content','protected','lastauthor','lastauthorid','category') VALUES('" . $article->authors . "','" . $article->title . "','" . $article->content . "','" . $article->protected . "','" . $article->lastauthor . "','" . $article->lastauthorid . "','" . $article->category . "',)";
                $sql = $db->write_query($query);
                if($db->error_number() > 0)
                {
                    flash_message($lang->wiki_import_error, 'error');
                    admin_redirect('index.php?module=wiki-import');
                }
                elseif(!$sql)
                {
                    flash_message($lang->wiki_import_error, 'error');
                    admin_redirect('index.php?module=wiki-import');
                }
                else
                {
                    flash_message($lang->wiki_import_success, 'success');
                    admin_redirect('index.php?module=wiki-import');
                }
            }
        }
        else
        {
            flash_message($lang->wiki_import_error, 'error');
            admin_redirect('index.php?module=wiki-import');
        }
    }
}

(我正在使用MyBB,其中包含flash_messageadmin_redirect的定义,可将用户重定向到另一个页面并显示消息。)

我的问题是我似乎无法上传它,也没有显示错误消息。此外,该页面只是刷新。内容示例如下:

<?xml version="1.0" ?>
<wiki>
    <article>
        <id>1</id>
        <title>To be Exported</title>
        <content>
            Export me!
        </content>
        <category>Meta</category>
        <lastauthor>admin</lastauthor>
        <lastauthorid>1</lastauthorid>
        <protected>0</protected>
        <authors>1</authors>
    </article>
</wiki>

文件上传框的idname属性为'xml_file'。我的本地主机上也有PHP版本5.3.13。

0 个答案:

没有答案