将从XML文件中提取的数据插入到MySQL表中

时间:2014-07-08 13:16:45

标签: php mysql sql arrays

我正在尝试将各种数据导出到MySQL中的现有数据库表中。下面是访问MySQL数据库和XML文档(edit.xml)的PHP代码,提取必要的数据并尝试将其放入表中Person

<?php

// create connection
$connect = mysqli_connect("localhost", "root", "****");
// check connection
if (!$connect) {
    die('Could not connect: ' . mysql_error());
    exit();
}

// select database
mysqli_select_db($connect, 'poeticarchive');

// save XML document as a variable reference
$xml = simplexml_load_file("edit.xml");

// search document for all <emph> elements with an attribute named 'altrender' that have the value 'identifier' (unique id value)
$aID = $xml -> xpath('//ead/archdesc/dsc/c01//c02[1]//@identifier');
// date of birth value
$dob = $xml -> xpath('//ead/archdesc/dsc/c01//c02[1]//emph[3]');
// first name value
$firstName = $xml -> xpath('//ead/archdesc/dsc/c01//c02[1]//emph[2]');
// last name value
$lastName = $xml -> xpath('//ead/archdesc/dsc/c01//c02[1]//emph[1]');
// biography value
$bio = $xml -> xpath('//ead/archdesc/dsc/c01/c02//c03/bioghist//p');
// books by author value
$book = $xml -> xpath('//ead/archdesc/dsc/c01/c02/c03/c04//unittitle | //ead/archdesc/dsc/c01/c02/c03/c04/c05//unittitle');

// store the values into an array
$person = array("AuthorID"=>$aID,
                "FirstName"=>$firstName,
                "LastName"=>$lastName,
                "Biography"=>$bio,
                "DateOfBirth"=>$dob,
                "Books"=>$book);

$personTable = implode("','",$person);

mysqli_query($connect, "INSERT INTO Person (AuthorID, FirstName, LastName, Biography, Books, DateOfBirth) VALUES ('$personTable')");

// close connection
mysqli_close($connect);

?>

这将提取我之后的数据(因为我使用while(list($key $value) = each($array))检查以在屏幕上显示数据)。但是它会出现错误Notice: Array to string conversion...。有谁知道如何迭代这个数组并将数据插入表Person

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

错误很清楚。 SimpleXML将值返回为数组。

您可以使用(string) $xml->path()轻松将其转换为字符串。

答案 1 :(得分:0)

你可以试试这个, 而不是

mysqli_query($connect, "INSERT INTO Person (AuthorID, FirstName, LastName, Biography, Books, DateOfBirth) VALUES ('$personTable')");

在插入查询中写入单个值 像这样

mysqli_query($connect, "INSERT INTO Person (AuthorID, FirstName, LastName, Biography, Books, DateOfBirth) VALUES (" . $aID . ", '" . $firstName . "'" . $lastName . "'" . $bio . "'" . $dob . "'" . $book ."')");