简体   繁体   中英

Inserting data extracted from an XML file into a MySQL table

I have a variety of data that I'm trying to export into an existing database table in MySQL. Below is the PHP code that accesses the MySQL database and the XML document (edit.xml), extracts the necessary data and attempts to place it into the table, 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);

?>

This extracts the data I'm after (as I checked using while(list($key $value) = each($array)) to display the data on-screen). However it comes up with the error Notice: Array to string conversion... . Does anyone know how I can iterate this array and insert the data into the table Person ?

Thank you for your help!

The error is clear enough. SimpleXML returns values as array.

You can easily convert it to string using (string) $xml->path() though.

you can try this, instead of

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

write individual values in insert query like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM